<?php defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

/* JoomLeague League Management and Prediction Game for Joomla!
 * Copyright (C) 2007  Robert Moss
 *  
 * Homepage: http://www.joomleague.de
 * Support: htt://www.joomleague.de/forum/
 * 
 * This file is part of JoomLeague.
 *  
 * JoomLeague is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * Please note that the GPL states that any headers in files and
 * Copyright notices as well as credits in headers, source files
 * and output (screens, prints, etc.) can not be removed.
 * You can extend them with your own credits, though...
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * The "GNU General Public License" (GPL) is available at
 * http://www.gnu.org/copyleft/gpl.html.
*/ 

// Activate JoomLeague error reporting
// error_reporting(E_ALL);

require_once $mainframe->getPath( 'class' );

//##########################################################################################################################
// Sprachauswahl Start
define( 'JLADMINBASEPATH', dirname(__FILE__) );
define ( "_JOOMLA_PATH", $mainframe->getCfg('absolute_path') );
define ( "JLFRONTPATH", _JOOMLA_PATH.'/components/com_joomleague' );
define('JLLIVEURL', $mainframe->getCfg('live_site'));
define('JLLANG', $mainframe->getCfg( 'lang' ));
if (file_exists($mosConfig_absolute_path.'/components/com_joomleague/language/'.$mosConfig_lang.'.php')) {
  include($mosConfig_absolute_path.'/components/com_joomleague/language/'.$mosConfig_lang.'.php');
} 
else{
  include($mosConfig_absolute_path.'/components/com_joomleague/language/english.php');
}

// Sprachauswahl Ende
//##########################################################################################################################

$jl_v = new JoomLeagueVersion();
$joomleague_version = $jl_v->version;

//$cid = mosGetParam($_POST, 'cid', array(0));
$cid = mosGetParam($_REQUEST, 'cid', array(0));
$gid = mosGetParam($_REQUEST, 'gid', '0');

$option = mosGetParam($_REQUEST , 'option' , 'com_joomleague');
$act = mosGetParam($_REQUEST , 'act' , 'projects'); //projects,clubs,teams,seasons etc
$task = mosGetParam($_REQUEST , 'task' , ''); //new,edit,save,delete etc
include_once( "includes/pageNavigation.php" );

$tab = "tab1"; //matrix
if(substr($task,0,3) == "tab"){
  $tab = $task;
  $task = "matrix";
}

if (!is_array($cid)){
  $cid = array(0);
}

if($act == 'projects' && $task == 'setactual'){
  $_SESSION["joomleague"] = $cid[0];
  session_unregister("joomleague_team");
  session_unregister("joomleague_match");
  //setCookie('joomleague', $cid[0]);
  //mosRedirect('index2.php?option=com_joomleague');
}

$project = null;
$team = null;

//$joomleague = intval(mosGetParam($_COOKIE, 'joomleague', 0));
$joomleague = intval(mosGetParam($_SESSION, 'joomleague', 0));
if($joomleague > 0){
  $project = new JoomLeague($database);
  $project->load($joomleague);
}

if($act == 'teamtool' && $task == 'setactual'){
  if (mosGetParam($_REQUEST, 'mypp', 0) > 0) $_SESSION["joomleague"] = mosGetParam($_REQUEST, 'mypp', 0);
  $_SESSION["joomleague_team"] = $cid[0];
  //setCookie('joomleague_team', $cid[0]);
  mosRedirect('index2.php?option=com_joomleague&act=playertool');
}

if($act == 'matches' && $task == 'event'){
  $_SESSION["joomleague_match"] = $cid[0];
  //setCookie('joomleague_match',$cid[0]);
  mosRedirect('index2.php?option=com_joomleague&act=matchevents');
}

//$joomleague_team = intval(mosGetParam($_COOKIE, 'joomleague_team', 0));
$joomleague_team = intval(mosGetParam($_SESSION, 'joomleague_team', 0));
if($joomleague_team > 0){
  $tl = new TeamTool($database);
  $tl->load($joomleague_team);
  
  $team = new JL_Team( $database );
  $team->load($tl->team_id);
}

switch($act){

  case 'JLimport':
  
    $view = 'components/com_joomleague/templates/edit_form_jl_import.tpl.php';
    
    $jl_version=$joomleague_version;
    require 'components/com_joomleague/templates/view.tpl.php'; 
    break;
      
  case 'template_config':
		switch($task){
		
			case 'reset':
  			$ids = implode(',', $cid);
  			$query="DELETE FROM #__joomleague_template_config WHERE id IN (".$ids.") AND project_id = ".$project->id;
  			$database->setQuery($query);
        $database->query();
  			mosRedirect( "index2.php?option=$option&act=template_config" );
  			break;
			
			case 'apply':
				$string="";
				foreach ($_POST AS $key=>$value) {
					if ($key !="option" && $key !="act" && $key !="task" && $key !="id") {
						$value= ereg_replace("(\r\n|\n|\r)", "", $value);
						$string.= "$key=$value\n";
					}
				} 
				$query="UPDATE #__joomleague_template_config SET params = '".$string."' WHERE id = ".$_POST['id'];
				$database->setQuery($query);
        $database->query();
				mosRedirect( "index2.php?option=$option&act=template_config&task=edit&cid[0]=".$_POST['id'] );
        break;
        
      case 'save':
			  $string="";
				foreach ($_POST AS $key=>$value) {
					if ($key !="option" && $key !="act" && $key !="task" && $key !="id") {
						$value= ereg_replace("(\r\n|\n|\r)", "", $value);
						$string.= "$key=$value\n";
						if ($key=='use_tip_admin' && $value=='0') {
				          $query="UPDATE #__joomleague SET tip_admin = 0 WHERE id = ".$project->id;
                          $database->setQuery($query);
                          $database->query();
                        }
					}
				} 
				$query="UPDATE #__joomleague_template_config SET params = '".$string."' WHERE id = ".$_POST['id'];
				$database->setQuery($query);
                $database->query();
				$row = new TemplateConfig($database);
        $row->bind( $_POST );
	      $row->checkin();
				mosRedirect( "index2.php?option=$option&act=template_config" );
        break;
        
			case 'edit':
				$row = new TemplateConfig($database);
				$row->load($cid[0]);

        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( "index2.php?option=$option&act=template_config");
        }

        if ($cid[0]) {
           $row->checkout( $my->id );
        }
        
				if (substr($mosConfig_lang, 0, 6) == "german") $langfolder = "german";
				else $langfolder = $mosConfig_lang;
				
        if (is_dir($mosConfig_absolute_path.'/components/com_joomleague/frontend_config/'.$langfolder)) {
				// xml file for module
					$xmlfile = $mosConfig_absolute_path.'/components/com_joomleague/frontend_config/'.$langfolder.'/'.$row->template.'.xml';
				}
				else $xmlfile = $mosConfig_absolute_path.'/components/com_joomleague/frontend_config/english/'.$row->template.'.xml';
				
        $xml = new Xml;
				$iso = split( '=', _ISO );
				
				$out = $xml->parse($xmlfile, 'FILE', $iso[1]);

				$params = explode("\n", $row->params);

                foreach($params AS $param) {
                    if ($param!='') {
					  list ($name, $value)= explode("=", $param);
					  $configvalues[$name]=$value;
					}
				}

				//echo "</pre></div>";
				$view = 'components/com_joomleague/templates/edit_form_templates.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php'; 
        break;
        
			case 'cancel':
				$row = new TemplateConfig($database);
        $row->bind( $_POST );
	      $row->checkin();
				mosRedirect( "index2.php?option=$option&act=template_config" );
        break;
			
      default:
  			if (substr($mosConfig_lang, 0, 6) == "german") $langfolder = "german";
  			else $langfolder = $mosConfig_lang;
  			
        if (is_dir($mosConfig_absolute_path.'/components/com_joomleague/frontend_config/'.$langfolder)) {
  				$xmldir = $mosConfig_absolute_path.'/components/com_joomleague/frontend_config/'.$langfolder;
  			}
        else $xmldir = $mosConfig_absolute_path.'/components/com_joomleague/frontend_config/english';
			
        if ($handle = opendir($xmldir)) {
          /* check that each xml template has a corresponding record in the 
          database for this project. If not, create the rows with default values
          from the xml file */
		      while ( $file = readdir($handle) ) {
            if ( $file != "." && $file != ".." && strtolower(substr($file, -3))=='xml') 
            {
  		    		$template=substr($file, 0, (strlen($file)-4));
  		        $query="SELECT id FROM #__joomleague_template_config WHERE project_id = $project->id
  		                                                                AND template = '".$template."'";
  		        $database->setQuery($query);
  		        if ($id=$database->loadResult()) 
              {
  		        	//template present in db for this project 							
  		        }
  		        else 
              {
  		        	//template not present, create a row with default values
  			        $xml = new Xml;
  							$out = $xml->parse($xmldir."/".$file, 'FILE', substr(_ISO,8) );
  							$temp='';
  							foreach ( $out["params"]["param-ATTR"] as $param )
  							{
                  if ($param["type"]!="spacer") $temp.=$param["name"]."=".$param["default"]."\n";
                }
  							$query = "INSERT INTO #__joomleague_template_config (template, func, title, params, project_id) VALUES
  										('".$template."', '".$out["func"]."', '".$out["name"]."', '".trim($temp)."', ".$project->id.")";
  							$database->setQuery($query);
  							//echo error, allows to check if there is a mistake in the template file
  							if (!$database->query()) echo "<b>Error in $template:</b> ".$database->getErrorMsg().'<br/>';
  		      	}
  		      }
		      }
          closedir($handle);
        }
        
		    $query="SELECT jtc.*, a.joomleague_admin, u.name AS editor
                      FROM #__joomleague_template_config AS jtc
                 LEFT JOIN #__joomleague AS a ON a.id = jtc.project_id
                 LEFT JOIN #__users AS u ON u.id = jtc.checked_out
                     WHERE jtc.project_id = $project->id
		          ORDER BY published, jtc.title ASC";      
				
        $database->setQuery($query);
        $rows = $database->loadObjectList();
       
        $view = 'components/com_joomleague/templates/edit_list_templates.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php'; 
        break;
    }
    break;
     
	case 'countries':
    switch($task){
    	case 'new':
      case 'edit':
        $row = new Country( $database );
        $row->load( $cid[0] );
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( "index2.php?option=$option");
        }
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        $view = 'components/com_joomleague/templates/edit_form_countries.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';
      break;
      case 'unpublish';
        $row = new Country( $database );
        $row->publish_array($cid, $_POST, 0, $my->id);
        mosRedirect("index2.php?option=$option&act=$act");
      break;
      case 'publish':
        $row = new Country( $database );
        $row->publish_array($cid, $_POST, 1, $my->id);
        mosRedirect("index2.php?option=$option&act=$act");
      break;
      case 'save':
        $row = new Country( $database );
        $row->bind( $_POST );
        $row->save($_POST, "");
	    	$row->checkin();
        mosRedirect("index2.php?option=$option&act=$act");
      break;
      case 'cancel':
        $row = new Country( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( "index2.php?option=$option&act=$act");
      break;
      default:
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );

        $search = $mainframe->getUserStateFromRequest( "search{$option}{$act}", 'search', '' );
	      $search = $database->getEscaped( trim( strtolower( $search ) ) );
        
        $where = array();
        if ($search) {
            $where[] = "LOWER(a.countries_iso_code_3) LIKE '$search%'";
	      }
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_countries AS a"
                          . (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
        );
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );

        $countries = array();
        $query="SELECT * FROM #__joomleague_countries AS a"
		      . (count( $where ) ? " WHERE " . implode( ' AND ', $where ) : "").
			   " ORDER BY published DESC, countries_iso_code_3 LIMIT $pageNav->limitstart,$pageNav->limit";
				
        $database->setQuery($query);
        $rows = $database->loadObjectList();
       
        $view = 'components/com_joomleague/templates/edit_list_countries.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php'; 
      }
  break;
	case "editEvents":
	$mid=intval(mosGetParam($_REQUEST, "mid", 0));
	$teamadmin=$project->getMatchAdmin($mid);
	if($my->id == $teamadmin || $my->id == $project->joomleague_admin || $my->id == $project->joomleague_editor || $my->usertype == 'Administrator' || $my->usertype == 'Super Administrator')
    {
		
		$mytask=mosGetParam($_REQUEST, "mytask",'');
		switch($mytask):
		case "savesquads":
		$homesquad=mosGetParam($_REQUEST, "home",'');
		$awaysquad=mosGetParam($_REQUEST, "away",'');
		$mid=intval(mosGetParam($_REQUEST, "mid",''));
		$query="UPDATE #__joomleague_matches SET homeroster = '".substr($homesquad, 0, strlen($homesquad)-1)."', awayroster = '".substr($awaysquad, 0, strlen($awaysquad)-1)."' WHERE match_id = $mid";
		$database->setQuery($query);
		if (!$database->query()) {
			echo "<span style='color:#ff0000;'><b>ERROR SAVING DATA</b><br /></span>";
		}
		else echo "<span style='color:#00ff00;'><b>DATA HAS BEEN UPDATED SUCCESSFULLY</b><br /></span>";

		//echo "<br />HOME: ".substr($homesquad, 0, strlen($homesquad)-1)."<br />AWAY: ".substr($awaysquad, 0, strlen($awaysquad)-1)."<br />MATCH: $mid";
		break;
		case "saveevent":
			$event_time=mosGetParam($_REQUEST, "event_time",'');
			$player_id=intval(mosGetParam($_REQUEST, "player_id",0));
			$notice=mosGetParam($_REQUEST, "notice",'');
			$eventtype=intval(mosGetParam($_REQUEST, "event_type_id",0));
			$event_sum=intval(mosGetParam($_REQUEST, "event_sum",1));
			if($player_id!=0&&$eventtype!=0) {
				$query="INSERT INTO #__joomleague_match_events (match_id, player_id, event_time, event_type_id, event_sum, project_id, notice)
				VALUES ($mid, $player_id, '$event_time', $eventtype, $event_sum, $project->id, '$notice')";
				$database->setQuery($query);
				$database->query();
			}
			else echo "<span style='color:#ff0000;'><b>NO PLAYER AND / OR EVENT HAS BEEN SENT!!</b></span>";
		break;
		case "deleteevent":
			$event_id=intval(mosGetParam($_REQUEST, "evid",'0'));
			if($event_id!=0) {
				$query="DELETE FROM #__joomleague_match_events WHERE event_id = $event_id";
				$database->setQuery($query);
				$database->query();
			}
			else echo "<span style='color:#ff0000;'><b>DELETE EVENT - NO PLAYER AND / OR EVENT HAS BEEN SENT!!</b></span>";
		break;
		case "updateevent":
			$event_id=intval(mosGetParam($_REQUEST, "evid",0));
			$event_sum=intval(mosGetParam($_REQUEST, "event_sum",1));
			$event_time=mosGetParam($_REQUEST, "event_time",'');
			if ($event_time=="") $event_time="NULL";
			$player_id=intval(mosGetParam($_REQUEST, "player_id",0));
			$notice=mosGetParam($_REQUEST, "notice",'');
			$eventtype=intval(mosGetParam($_REQUEST, "event_type_id",0));
			if ($player_id!=0&&$eventtype!=0&&$event_id!=0) {
				$query = "UPDATE #__joomleague_match_events SET player_id = $player_id, event_time = $event_time, notice = '$notice', event_type_id = $eventtype, event_sum = $event_sum WHERE event_id = $event_id";
				$database->setQuery($query);
				if (!$database->query()) {
					echo "<span style='color:#ff0000;'><b>ERROR SAVING DATA</b><br /></span>";
				}
				else echo "<span style='color:#00ff00;'><b>DATA HAS BEEN UPDATED SUCCESSFULLY</b><br /></span>";
			}
			else echo "<span style='color:#ff0000;'><b>YOU CAN NOT SET PLAYER AND / OR EVENTTYPE TO EMPTY VALUES!</b><br /></span>";
		endswitch;
		$match = new Match($database);
  	$match->load($mid);
		$matches=array();
		$matches[0]=$match;
		$team1 = new JL_Team($database);
    $team1->load($match->matchpart1);
    
    $team2 = new JL_Team($database);
    $team2->load($match->matchpart2);
    $homesquad=explode(";", trim($match->homeroster));
    foreach ($homesquad AS $player) $temphome[]->value = $player;
    $awaysquad=explode(";", trim($match->awayroster));
    foreach ($awaysquad AS $player) $tempaway[]->value = $player;
		$sortedevents=array();
		$eventtypes=$project->getEventTypes();
		$sortedevents = $project->jlmatchevents ($matches);
		$eventtypeoptions[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_EVENT );
		foreach ($eventtypes AS $eventtype) {
			$eventtypeoptions[] = mosHTML::makeOption( $eventtype->id, "$eventtype->name" );
		}
		$query = sprintf("SELECT pl.id, pl.firstname,pl.lastname, pos.name AS positionname
                      FROM #__joomleague_players pl
                      LEFT JOIN #__joomleague_playertool pt
                      ON pl.id = pt.player_id
                      LEFT JOIN #__joomleague_positions AS pos
                      ON pos.id = pt.position_id
                      WHERE team_id = %s AND
                      pt.project_id = %s ORDER BY pos.ordering, pl.lastname",$match->matchpart1,$project->id);
        
		$database->setQuery($query);
		$homeplayers = $database->loadObjectList();
    $homeoptions[] = mosHTML::makeOption( 0, _JL_ADMIN_SELECT_PLAYER );
    foreach($homeplayers as $result){
    	$homeoptions[] = mosHTML::makeOption($result->id, sprintf("%s, %s (%s)", $result->lastname, $result->firstname, $result->positionname)); 
    	$homesquadoptions[] = mosHTML::makeOption($result->id, sprintf("%s, %s (%s)", $result->lastname, $result->firstname, $result->positionname));
    }
    $query = sprintf("SELECT pl.id, pl.firstname,pl.lastname, pos.name AS positionname
                      FROM #__joomleague_players pl
                      LEFT JOIN #__joomleague_playertool pt
                      ON pl.id = pt.player_id
                      LEFT JOIN #__joomleague_positions AS pos
                      ON pos.id = pt.position_id
                      WHERE team_id = %s AND
                      pt.project_id = %s ORDER BY pos.ordering, pl.lastname",$match->matchpart2,$project->id);
        
		$database->setQuery($query);
		$guestplayers = $database->loadObjectList();
    $guestoptions[] = mosHTML::makeOption( 0, _JL_ADMIN_SELECT_PLAYER );
    foreach($guestplayers as $result){
    	$guestoptions[] = mosHTML::makeOption($result->id, sprintf("%s, %s (%s)", $result->lastname, $result->firstname, $result->positionname));
    	$guestsquadoptions[] = mosHTML::makeOption($result->id, sprintf("%s, %s (%s)", $result->lastname, $result->firstname, $result->positionname)); 
    }
		require 'components/com_joomleague/templates/edit_events.tpl.php';
	}
	else echo "<span style='color:#ff0000;'><b>YOU ARE NOT ALLOWED!!!<br /></span>";
	break;
  case "editmatch":
	$mytask=mosGetParam($_REQUEST, "mytask", '');
	$mid=intval(mosGetParam($_REQUEST, "mid", 0));
	$teamadmin=$project->getMatchAdmin($mid);
	if($my->id == $project->joomleague_admin || $my->id == $project->joomleague_editor || $my->usertype == 'Administrator' || $my->usertype == 'Super Administrator') {
		$match = new Match($database);
	 	$match->load($mid);
			switch ($mytask):
			case "cancel":
	  	$match->checkin( $mid );
			break;
			case "load":
				if (is_null($match->playground_id)) {
					$homteamtoolid=$project->getTeamtool_id($match->matchpart1);
					$playgroundtt=new TeamTool($database);
					$playgroundtt->load($homteamtoolid);
					$selected_playground=$playgroundtt->standard_playground;
				}
				else $selected_playground=$match->playground_id;
				$playgrounds[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_PLAYGROUND );
        $database->setQuery( "SELECT id AS value, name AS text FROM #__joomleague_playgrounds ORDER BY name");
        $playgrounds = array_merge( $playgrounds, $database->loadObjectList() );
        $playgroundslist = mosHTML::selectList( $playgrounds, 'playground_id'.$match->match_id, 'class="inputbox" style="font-size:9px;" size="1"','value', 'text', $selected_playground );
			  $match->checkout( $my->id );
			  $team1 = new JL_Team($database);
			  $team1->load($match->matchpart1);
				$team2 = new JL_Team($database);
			  $team2->load($match->matchpart2);
			  $teams = $project->getTeams();
			  $teamsoptions[] = mosHTML::makeOption(0,_JL_CHOOSE_TEAM);
			 	foreach ($teams AS $team) {
			 		$teamsoptions[] = mosHTML::makeOption($team->id, $team->name);
				}
	  require ('templates/edit_match.tpl.php');
	  break;
	  endswitch;
	  break;
	}
  case 'updates':
    
    $id = intval(mosGetParam($_REQUEST, 'id', 0));
    $view = 'components/com_joomleague/templates/edit_list_updates.tpl.php';
// new status important for new DB-Structure (possibility of revert changes - necessary?
    $status=intval(mosGetParam($_REQUEST, 'status', 0));
    switch($id){
      case 1: $view = "components/com_joomleague/updates/update_0.80_to_0.85.php";break;
      case 2: $view = "components/com_joomleague/updates/update_0.85_to_0.86.php";break;
// new case to update to introduce DB changes one round per matchday
      case 3: $view = "components/com_joomleague/updates/update_0.86_to_0.86a.php";break;
      case 4: $view = "components/com_joomleague/updates/update_0.86a_to_0.90.php";break;
      case 5: $view = "components/com_joomleague/updates/update_0.90_to_0.91.php";break;
      case 345 : $view = "components/com_joomleague/updates/patch_0.91_hockey.php";break;
    }
    
    $jl_version=$joomleague_version;
    require 'components/com_joomleague/templates/view.tpl.php';  
  
  break;
  
  case 'import':
    
    $id = intval(mosGetParam($_REQUEST, 'id', 0));
    $view = 'components/com_joomleague/templates/edit_list_imports.tpl.php';
    
    switch($id){
      case 1: $view = "components/com_joomleague/imports/jl_buli_06_07.php";break;
      case 2: $view = "components/com_joomleague/imports/jl_events.php";break;
      case 3: $view = "components/com_joomleague/imports/jl_referees.php";break;
      case 4: $view = "components/com_joomleague/imports/jl_buli_07_08.php";break;
      case 5: $view = "components/com_joomleague/imports/jl_playgrounds.php";break;
      case 6: $view = "components/com_joomleague/imports/jl_countries.php";break;
    }
    
    $jl_version=$joomleague_version;
    require 'components/com_joomleague/templates/view.tpl.php'; 
  
  break;  
  
    case 'LMOimport':
    
    $id = intval(mosGetParam($_REQUEST, 'id', 0));
    $view = 'components/com_joomleague/templates/edit_list_lmo_import.tpl.php';
    
    switch($id){
      case 1: $view = "components/com_joomleague/imports/lmoImport.php";break;

    }
    
    $jl_version=$joomleague_version;
    require 'components/com_joomleague/templates/view.tpl.php';  
  
  break;  
  
  case 'frontend':
  
    $teams = $project->getTeams();
    
    $view = 'components/com_joomleague/templates/edit_frontend.tpl.php';    
    $jl_version=$joomleague_version;
    require 'components/com_joomleague/templates/view.tpl.php'; 
  
  break;
  
  case 'tips':
    
    switch($task){
      
      case 'send':
        $project_id = $mainframe->getUserStateFromRequest( "project{$option}", 'project_id', 0 );      
        if ($project_id > 0) {
          $projecttip = new JoomLeague($database);
          $projecttip->load($project_id);
          $showUser_config=$projecttip->getTemplateConfig("show_user.tpl");
        }
        $query = "SELECT current_round FROM #__joomleague WHERE id = $project_id";
        $database->setQuery($query);
        $current_round = $database->loadResult();
        
        $query = "SELECT user_id FROM #__joomleague_tip_members WHERE reminder = 1 AND project_id = $project_id";
        $database->setQuery($query);
        $reminder = $database->loadResultArray();
        $reminderlist = implode(",",$reminder);

        $query = "SELECT name, email FROM #__users WHERE id IN ($reminderlist)";
        $database->setQuery($query);
        $adresses = $database->loadObjectList();

        $mailsubject = str_replace('$DATE$', $thisdate, trim($showUser_config['reminder_subject']));
        $mailsubject = str_replace('$ROUND$', $current_round, $mailsubject);
        $mailsubject = str_replace('$URL$', $mosConfig_live_site, $mailsubject);

        $mailfooter = str_replace('$DATE$', $thisdate, trim($showUser_config['reminder_footer']));
        $mailfooter = str_replace('$ROUND$', $current_round, $mailfooter);
        $mailfooter = str_replace('$URL$', $mosConfig_live_site, $mailfooter);
        $mailfooter = str_replace('$NL$', "\n", $mailfooter);
        $mailfooter = str_replace('$DL$', "\n\n", $mailfooter);        

        $newline="\n";         
 
// Reminder Content - START        
        foreach ($adresses AS $adress) {
        $mailheader = str_replace('$DATE$', $thisdate, trim($showUser_config['reminder_intro']));
        $mailheader = str_replace('$ROUND$', $current_round, $mailheader);
        $mailheader = str_replace('$URL$', $mosConfig_live_site, $mailheader);
        $mailheader = str_replace('$NL$', "\n", $mailheader);
        $mailheader = str_replace('$DL$', "\n\n", $mailheader);
        $mailheader = str_replace('$NAME$', $adress->name, $mailheader);
        mosMail( $mosConfig_mailfrom, $mosConfig_fromname, $adress->email, $mailsubject, $mailheader.$newline.$mailmessage.$newline.$mailfooter, 0 );
		}
// Reminder Content - END  
       
       	$msg = 'Reminder sent to '. count( $adresses ) .' users';
	      mosRedirect( 'index2.php?option=com_joomleague&act=tips', $msg );
      break;
      
      case 'approve':
        $member = new TipMember($database);
        $member->approve($cid, $_POST, 1);
        mosRedirect("index2.php?option=com_joomleague&act=tips");
      break;
      
      case 'reject':
        $member = new TipMember($database);
        $member->approve($cid, $_POST, 0);
        mosRedirect("index2.php?option=com_joomleague&act=tips");
      break;
      
      case 'remove':
        $member = new TipMember($database);
		if (!$_POST['project_id']) {
          mosRedirect("index2.php?option=com_joomleague&act=tips", "No Project selected");
		} else {
          $member->deleteUserTips($cid, $_POST, 0);
          mosRedirect("index2.php?option=com_joomleague&act=tips");
		}
      break;
      
      default:
        
        $project_id = $mainframe->getUserStateFromRequest( "project{$option}", 'project_id', 0 );
	      $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
	      $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        
        $where = array();
        
        if ($project_id > 0) {
		      $where[] = "m.project_id = '$project_id'";
	      }
        
      
        $projects[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_PROJECT );      
        
        $query = "SELECT id as value, name as text 
                    FROM #__joomleague 
                   WHERE joomleague_tip = 1 and published";
        $database->setQuery($query);
        $projects = array_merge( $projects, $database->loadObjectList() );
        
        $projectlist = mosHTML::selectList( $projects, 'project_id', 'class="inputbox" onchange="document.adminForm.submit();" size="1"','value', 'text', $project_id );
        unset( $projects );
        
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_tip_members AS m"
		      . (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
	      );
	      $total = $database->loadResult();
        
        require_once( $GLOBALS['mosConfig_absolute_path'] . '/administrator/includes/pageNavigation.php' );
	      $pageNav = new mosPageNav( $total, $limitstart, $limit  );

	      $database->setQuery( "SELECT m.*, p.name AS project, u.username, u.name"
		      . "\nFROM #__joomleague_tip_members AS m"
		      . "\nLEFT JOIN #__joomleague AS p ON p.id = m.project_id"
		      . "\nLEFT JOIN #__users AS u ON u.id = m.user_id"
		      . (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
		      . "\nORDER BY m.project_id, username"
		      . "\nLIMIT $pageNav->limitstart,$pageNav->limit"
	      );

	      $rows = $database->loadObjectList();
       
        $view = 'components/com_joomleague/templates/edit_list_tipmembers.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';
        
      break;
    }
  break;
  
  case 'matches':
    
    switch($task){
      
      case 'new':
      case 'edit':
        $row = new Match( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( "index2.php?option=$option");
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        $homesquad=explode(";", trim($row->homeroster));
		    foreach ($homesquad AS $player) $temphome[]->value = $player;
		    $awaysquad=explode(";", trim($row->awayroster));
		    foreach ($awaysquad AS $player) $tempaway[]->value = $player;
		    
		    $query = sprintf("SELECT pl.id, pl.firstname,pl.lastname, pos.name AS positionname
                          FROM #__joomleague_players pl
                          LEFT JOIN #__joomleague_playertool pt
                          ON pl.id = pt.player_id
                          LEFT JOIN #__joomleague_positions AS pos
                          ON pos.id = pt.position_id
                          WHERE team_id = %s AND
                          pt.project_id = %s ORDER BY pos.ordering, pl.lastname",$row->matchpart1,$project->id);
        
    		$database->setQuery($query);
    		$homeplayers = $database->loadObjectList();
        foreach($homeplayers as $result){
        	$homesquadoptions[] = mosHTML::makeOption($result->id, sprintf("%s, %s (%s)", $result->lastname, $result->firstname, $result->positionname));
        }
        $query = sprintf("SELECT pl.id, pl.firstname,pl.lastname, pos.name AS positionname
                          FROM #__joomleague_players pl
                          LEFT JOIN #__joomleague_playertool pt
                          ON pl.id = pt.player_id
                          LEFT JOIN #__joomleague_positions AS pos
                          ON pos.id = pt.position_id
                          WHERE team_id = %s AND
                          pt.project_id = %s ORDER BY pt.position_id, pl.lastname",$row->matchpart2,$project->id);
            
    		$database->setQuery($query);
    		$guestplayers = $database->loadObjectList();
        foreach($guestplayers as $result){
        	$guestsquadoptions[] = mosHTML::makeOption($result->id, sprintf("%s, %s (%s)", $result->lastname, $result->firstname, $result->positionname)); 
        }
    
        /*hack: referee is one other team*/
        if ($project->teams_as_referees)
        {
          $query = "SELECT id, name, short_name FROM #__joomleague_teams ORDER BY name";        	
        	
        	$database->setQuery($query);
          $results = $database->loadObjectList();
          $ref[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_REFEREE );
          foreach($results as $result){
          	$ref[] = mosHTML::makeOption($result->id, sprintf("%s", $result->name)); 
          }
        }
        else
        {
          $query = "SELECT id, firstname, lastname FROM #__joomleague_referees ORDER BY lastname";
       	
        	$database->setQuery($query);
          $results = $database->loadObjectList();
          $ref[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_REFEREE );
          foreach($results as $result){
          	$ref[] = mosHTML::makeOption($result->id, sprintf("%s, %s", $result->lastname, $result->firstname)); 
          }
        }

        $refereelist = mosHTML::selectList( $ref, 'referee_id', 'class="inputbox" size="1"','value', 'text', $row->referee_id );
        unset($ref);
        
        
        $team1 = new JL_Team( $database );
        $team1->load( $row->matchpart1);
        
        $team2 = new JL_Team( $database );
        $team2->load( $row->matchpart2);
        
        $view = 'components/com_joomleague/templates/edit_form_matches.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';    
         
      break;
      
      case 'save':
        $row = new Match( $database );
		$row->save_array($_POST['match_id'],$_POST);
        $row->bind( $_POST );
	    $row->checkin();
        mosRedirect("index2.php?option=$option&act=$act");
      break;
      
      case 'cancel':
        $row = new Match( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'publish':
        $round = (intval(mosGetParam($_REQUEST,'round', 0)) > 0) ? $_REQUEST["round"] : $project->current_round;
        
        $row = new Match( $database );
        $row->publish_array($cid, $_POST, 1, $my->id);
        mosRedirect("index2.php?option=$option&act=$act&round=$round");
      break;
      
      case 'unpublish';
        $round = (intval(mosGetParam($_REQUEST,'round', 0)) > 0) ? $_REQUEST["round"] : $project->current_round;
        
        $row = new Match( $database );
        $row->publish_array($cid, $_POST, 0, $my->id);
        mosRedirect("index2.php?option=$option&act=$act&round=$round");
      break;
      
      case 'remove':
        $round = (intval(mosGetParam($_REQUEST,'round', 0)) > 0) ? $_REQUEST["round"] : $project->current_round;
        
        $row = new Match( $database );
        $row->removeMatch($cid);
        mosRedirect("index2.php?option=$option&act=$act&round=$round");
      break;
      
      
      default:
        
        $round = (intval(mosGetParam($_REQUEST,'round', 0)) > 0) ? $_REQUEST["round"] : $project->current_round;
        
        $rounds = array();
// added round_date_first, round_date_last to query and removed round_date
        $query="SELECT id, matchcode, name, round_date_first, round_date_last FROM #__joomleague_rounds WHERE project_id = $project->id order by matchcode,round_date_first";
        $database->setQuery($query);
        $results = $database->loadObjectList();
        $temp = array();
        foreach($results as $result){
          if(!in_array($result->name, $temp))
            $rounds[] = mosHTML::makeOption($result->matchcode, sprintf("%s", $result->name)); 
          array_push($temp, $result->name);
        }

        $round_list = mosHTML::selectList( $rounds, 'round', 'class="inputbox" 
                      onChange="javascript:document.roundForm.submit();" size="1"','value', 'text', $round );
        unset($rounds);
        $query= sprintf("SELECT m.*, t1.name AS team1, t2.name AS team2,  u.name AS editor
                                FROM #__joomleague_matches AS m
                           LEFT JOIN #__users AS u ON u.id = m.checked_out
                           LEFT JOIN #__joomleague_teams AS t1 ON t1.id = m.matchpart1
                           LEFT JOIN #__joomleague_teams AS t2 ON t2.id = m.matchpart2
                           LEFT JOIN #__joomleague_rounds AS r ON r.id = m.round_id
                 WHERE m.project_id = %s AND r.matchcode = %s",$project->id, $round);
        $database->setQuery($query);
        $rows = $database->loadObjectList();
        
        $view = 'components/com_joomleague/templates/edit_list_matches.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php'; 
        
      break;
    } 
    
  break;
  
  case 'matchevents':
    
    switch($task){
      
      case 'new':
      case 'edit':
        
        $row = new MatchEvent( $database );
        $row->load( $cid[0]);
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( "index2.php?option=$option");
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }

        $match = new Match( $database );
        $match->load( $_SESSION["joomleague_match"] );
        
        #we need Players of matchpart1 and matchpart2
        
        $query = sprintf("SELECT pl.id, pl.firstname,pl.lastname,
                          pos.name AS positionname, t.name AS teamname
                          FROM #__joomleague_players pl
                          LEFT JOIN #__joomleague_playertool pt
                          ON pl.id = pt.player_id
                          LEFT JOIN #__joomleague_positions AS pos
                          ON pos.id = pt.position_id
                          LEFT JOIN #__joomleague_teams AS t
                          ON t.id = pt.team_id
                          WHERE team_id in (%s,%s) AND
                          pt.project_id = %s ORDER BY t.id, pos.ordering",$match->matchpart1,$match->matchpart2,$project->id);
        
        $database->setQuery($query);
        $results = $database->loadObjectList();
        
        $options[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_PLAYER );
        foreach($results as $result){
            $options[] = mosHTML::makeOption($result->id, sprintf("%s, %s (%s - %s)", $result->lastname, $result->firstname, $result->teamname, $result->positionname)); 
        }

        $playerlist = mosHTML::selectList( $options, 'player_id', 'class="inputbox" size="1"','value', 'text', $row->player_id );
        unset($options);
        
        $options[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_EVENT );
        $database->setQuery( "SELECT id AS value, name AS text 
                                FROM #__joomleague_eventtypes" );
        $options = array_merge( $options, $database->loadObjectList() );

        $eventtypelist = mosHTML::selectList( $options, 'event_type_id', 'class="inputbox" size="1"','value', 'text', $row->event_type_id );
        unset( $options );
        
        $view = 'components/com_joomleague/templates/edit_form_matchevents.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php'; 
        
      break;
      
      case 'save':
        $matchevent = new Matchevent( $database );
        //if (!$_POST['event_sum']) $_POST['event_sum']=1;
        $matchevent->save($_POST, "");
        mosRedirect("index2.php?option=$option&act=$act");
      break;
      
      case 'cancel':
        $row = new Matchevent( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'remove':
        $row = new Matchevent( $database );
        $row->delete_array($cid, $my->id);
        mosRedirect("index2.php?option=$option&act=$act");
      break;
      
      default:
        $match = new Match( $database );
        $match->load( $_SESSION["joomleague_match"] );
        
        $query = sprintf("SELECT e.*, p.lastname as lastname, p.firstname as firstname, et.name as event_type_name,
        u.name as checkoutuser, a.joomleague_admin, a.joomleague_editor
                            FROM #__joomleague_match_events e
                       LEFT JOIN #__joomleague_players p on p.id = e.player_id
                       LEFT JOIN #__joomleague_eventtypes et on et.id = e.event_type_id
                       LEFT JOIN #__joomleague a on e.project_id = a.id
                       LEFT JOIN #__users u on e.checked_out = u.id
                           WHERE match_id = %s 
                        ORDER BY e.event_time", $_SESSION["joomleague_match"]);
        $database->setQuery($query);
        $rows = $database->loadObjectList();
        
        $view = 'components/com_joomleague/templates/edit_list_matchevents.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';  
        
      break;
    }
  break;
  
  case 'rounds':
    
    switch($task){
      
      case 'new':
      case 'edit':
        $row = new Round( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( "index2.php?option=$option");
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        
        $view = 'components/com_joomleague/templates/edit_form_rounds.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';   
        
        break;
      
      case 'return':
        $round = new Round( $database );
        foreach ($cid as $rid) {
          $round->load($rid);
          $games = $round->getMatches();
          $round->set('name', $round->name.' return');
          $round->set('matchcode', $round->matchcode+1000);
          $round->set('id', NULL); //to trigger creation
          $round->store();
          
          $return = new Match( $database );
          $first_leg = new Match( $database );
          foreach ($games as $game) {
            $first_leg->load( $game );
            $return->set( 'matchpart1', $first_leg->matchpart2 );
            $return->set( 'matchpart2', $first_leg->matchpart1 );
            $return->set( 'project_id', $first_leg->project_id );
            $return->set( 'round_id', $round->id );
            $return->set( 'match_id', NULL );
            //print_r($return);
            $return->store();
          }
        }
        unset ($round,$games, $return,$first_leg);
        mosRedirect( "index2.php?option=$option&act=$act" );
        break;
      
      case 'save':
        $row = new Round( $database );
        $row->save($_POST, "project_id = $project->id");
        mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'cancel':
        $row = new Round( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'savematches':
        $row = new Match( $database );
		foreach($cid as $cids) {
			$row->save_array($cids,$_POST,true);
	        $row->checkin( $cids );
		}
        mosRedirect("index2.php?option=$option&act=$act&task=tab2&round=".$_POST['id']);
      break;
      
      case 'publishmatches':
        $row = new Match( $database );
        $round = $row->publish_array($cid, $_POST, 1, $my->id);
        mosRedirect("index2.php?option=$option&act=$act&task=tab2&round=$round");
      break;
        
      case 'deletematches':
        $row = new Match( $database );
        $round = $row->removeMatch($cid);
        mosRedirect("index2.php?option=$option&act=$act&task=tab2&round=$_POST[round]");
      break;
      
      case 'unpublishmatches':
        $row = new Match( $database );
        $round = $row->publish_array($cid, $_POST, 0, $my->id);
        mosRedirect("index2.php?option=$option&act=$act&task=tab2&round=$round");
      break;
      
      case 'setmatchesnull':
        $row = new Match( $database);
        $round = $row->setNull($cid, $_POST, $my->id);
        mosRedirect("index2.php?option=$option&act=$act&task=tab2&round=$round");
      break;
      
      case 'remove':
        $round = new Round( $database );
        if (!$round->deleteRound($cid)) {
          mosRedirect( "index2.php?option=$option&act=$act", "Please delete Matches first");
		} else {
          mosRedirect( "index2.php?option=$option&act=$act");
		}
      break;
      
      case 'matrix':
                        
        if(isset($_POST['func']) && mosGetParam($_POST,'func','') == 'savematch'){
          $match = new Match( $database );
          $match->bind( $_POST );
          $match->save(array(),false);
        }   
        
        $round = intval(mosGetParam($_REQUEST,'round', 0)); 
        if($round == 0) $round = $cid[0];  
      
        $row = new Round( $database );
        $row->load( $round );
   
        $myrounds = $project->getRoundNames();
        foreach($myrounds as $result){
            $datum = mosFormatDate($result->round_date_first.' 00:00:00', '%d.%m.%Y', $project->serveroffset);
            if ($result->round_date_last!='0000-00-00') $datum .= '-'.mosFormatDate($result->round_date_last.' 00:00:00', '%d.%m.%Y', $project->serveroffset);
            $rounds[] = mosHTML::makeOption($result->id, sprintf("%s  (%s)", $result->name,$datum)); 
        }
        
        $round_list = mosHTML::selectList( $rounds, 'round', 'class="inputbox" 
                      onChange="javascript:document.roundForm.submit();" size="1"','value', 'text', $row->id );
        unset($rounds);
        $matches = $project->getResults($row->matchcode, "ASC", 1);
        $match_list = array();
        $mdd[] = mosHTML::makeOption( 0, _JL_ADMIN_EDIT_LIST_MATCHES_TITLE );
      
foreach($matches as $v){
				$match = new Match($database);
				$match->load($v->match_id);
				$home = new JL_Team($database);
				$home->load($match->matchpart1);
				$away = new JL_Team($database);
				$away->load($match->matchpart2);
				if (!$match->checked_out || $match->checked_out == $my->id || strtolower($my->usertype) == 'super administrator') {
          $match_list[] = $match->matchpart1.'_'.$match->matchpart2;
          $mdd[] = mosHTML::makeOption( "index3.php?option=com_joomleague&act=editEvents&p=".$project->id."&mid=".$match->match_id."&no_html=1", $home->short_name." - ".$away->short_name );
        }
      }
    	   
      	/*hack: referee is one other team*/
        if ($project->teams_as_referees)
        {
          $query = "SELECT id, name, short_name FROM #__joomleague_teams ORDER BY name";        	
        	
        	$database->setQuery($query);
          $results = $database->loadObjectList();
          $ref[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_REFEREE );
          foreach($results as $result){
          	$ref[] = mosHTML::makeOption($result->id, sprintf("%s", $result->name)); 
          }
        }
        else
        {
          $query = "SELECT id, firstname, lastname FROM #__joomleague_referees ORDER BY lastname";
       	
        	$database->setQuery($query);
          $results = $database->loadObjectList();
          $ref[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_REFEREE );
          foreach($results as $result){
          	$ref[] = mosHTML::makeOption($result->id, sprintf("%s, %s", $result->lastname, $result->firstname)); 
          }
        }
       
        $teams = $project->getTeams();
        $matrix ='';
        if (count($teams) <= 20) {
        $matrix = "<table width=\"100%\" class=\"adminlist2\">";
         
         $k = 0;
         for($rows = 0; $rows <= count($teams); $rows++){
          if($rows == 0) $trow = $teams[0];
          else $trow = $teams[$rows-1];
          
          
          $matrix .= "<tr class=\"row$k\">";
          
            for($cols = 0; $cols <= count($teams); $cols++){
              
              $text = '';
              $checked = '';
              $color = 'white';
              
              if( $cols == 0 ) $tcol = $teams[0]; 
              else $tcol = $teams[$cols-1];
              
              $match = $trow->id.'_'.$tcol->id;
                
              if(in_array($match,$match_list)){
                $checked = 'checked';
                $color = 'teal';
              }
              
              if($rows == 0 && $cols == 0) $text = sprintf("<td align=\"center\"><b>%s</b></td>",$project->name);
              else if($rows == 0) $text = sprintf("<td width=\"200\" align=\"center\" title=\"%s\">%s</td>",$tcol->name,$tcol->short_name); //picture columns
              else if($cols == 0) $text = sprintf("<td align=\"left\" nowrap>%s</td>",$trow->name); // named rows
              else if($rows == $cols) $text = "<td align=\"center\"><input type=\"radio\" DISABLED></td>"; //impossible matches
              else{
                $onClick = sprintf("onClick=\"javascript:SaveMatch('%s','%s','%s');\"",$trow->id,$tcol->id,$row->id);
                $text = sprintf("<td align=\"center\" title=\"%s - %s\" bgcolor=\"%s\"><input type=\"radio\" name=\"match_%s\" %s %s></td>\n",$trow->name,$tcol->name,$color,$trow->id.$tcol->id, $onClick, $checked);
              }
              $matrix .= $text;
            }
          $k = 1 - $k;
          
         }
          
         $matrix .= "</table>";
        }
         $view = 'components/com_joomleague/templates/edit_matrix_rounds.tpl.php';    
         $jl_version=$joomleague_version;
         require 'components/com_joomleague/templates/view.tpl.php';  
      
      break;
      
      default:        
//changed second ordering to round_date_first Gucky 2007/05/25    
        $database->setQuery( "SELECT r.*, u.name AS editor
                                FROM #__joomleague_rounds AS r
                           LEFT JOIN #__users AS u ON u.id = r.checked_out
                               WHERE r.project_id = ".$project->id."
                            ORDER BY r.matchcode, r.round_date_first");
        $rows = $database->loadObjectList();        
        
        $view = 'components/com_joomleague/templates/edit_list_rounds.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';   
        
      break;
    }
  break;
  
  case 'teamtool':
    
    switch($task){
      
      case 'saveAll':
        $project->assignTeams($_POST);
        mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'saveOne':
        $row = new TeamTool( $database );
        $row->save($_POST, "");
        mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'cancel':
        $row = new TeamTool( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      
      
      case 'edit':
        
        $row = new TeamTool( $database );
        $row->load($cid[0]);
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        
        $t = new JL_Team( $database);
        $t->load($row->team_id);
        
        $users[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_USER );
        $database->setQuery( "SELECT id AS value, name AS text 
                                FROM #__users " );
        $users = array_merge( $users, $database->loadObjectList() );

        $user_list = mosHTML::selectList( $users, 'admin', 'class="inputbox" size="1"','value', 'text', $row->admin );
        unset( $users );
        
        $divisions[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_DIVISION );
        $database->setQuery( "SELECT id AS value, name AS text 
                                FROM #__joomleague_divisions WHERE project_id=$project->id" );
                                
        $divisions = array_merge( $divisions, $database->loadObjectList() );
        $divisionlist = mosHTML::selectList( $divisions, 'division_id', 'class="inputbox" size="1"','value', 'text', $row->division_id );
        unset( $divisions );
        
        $playgrounds[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_PLAYGROUND );

        $database->setQuery( "SELECT id AS value, name AS text FROM #__joomleague_playgrounds ORDER BY name");
        $playgrounds = array_merge( $playgrounds, $database->loadObjectList() );
        $playgroundslist = mosHTML::selectList( $playgrounds, 'standard_playground', 'class="inputbox" size="1"','value', 'text', $row->standard_playground );
        $view = 'components/com_joomleague/templates/edit_form_teamtool.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';    
        
      break;
      
      case 'copy':
/*
        $row = new JL_Team( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id) {
          mosRedirect( "index2.php?option=$option");
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
*/

        $projects[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_PROJECT );

        $database->setQuery( "SELECT id AS value, name AS text FROM #__joomleague WHERE id <> $project->id");
        $projects = array_merge( $projects, $database->loadObjectList() );

        $clist = mosHTML::selectList( $projects, 'project_id', 'class="inputbox" size="1"','value', 'text', 0 );
        $cids = implode(",",$cid);
        $view = 'components/com_joomleague/templates/copy_form_teams.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';            

      break;

	  case 'copysave':
		if (isset($_POST["old_id"])) $old_id = $_POST["old_id"];
		if (isset($_POST["cids"])) $cids = $_POST["cids"];

        $database->setQuery( 'SELECT team_id, admin, info, checked_out, checked_out_time, picture, description, standard_playground FROM #__joomleague_team_joomleague WHERE project_id='.$old_id.' AND id IN ('.$cids.')');
        $results = $database->loadObjectList();
		
		foreach($results as $result) {
			$names = 'project_id, team_id, admin, info, checked_out, checked_out_time';
			$values = sprintf("'%s','%s','%s','%s','%s','%s'",$_POST['project_id'],$result->team_id,$result->admin,$result->info,$result->checked_out,$result->checked_out_time, $result->standard_playground);
			if (isset($result->picture)) {
				$names .= ', picture';
				$values .= sprintf(",'%s'",$result->picture);
			}
			if (isset($result->description)) {
				$names .= ', description';
				$values .= sprintf(",'%s'",$result->description);
			}
			$names .= ', standard_playground';
			if (isset($result->standard_playground)) {
				$values .= sprintf(",'%s'",$result->description);
			} else $values .= ', NULL';

			$query = "INSERT INTO #__joomleague_team_joomleague ($names) VALUES ($values)";
			$database->setQuery($query);
			$database->query($query);

	        $database->setQuery("SELECT * FROM #__joomleague_playertool WHERE project_id=$old_id AND team_id = $result->team_id");
    	    $results = $database->loadObjectList();

			foreach($results as $result) {
				$names = 'player_id,team_id,project_id,position_number,position_id,weight,height,injury,injury_date,injury_end,injury_detail,suspension,suspension_date,suspension_end,suspension_detail,picture,description,published,checked_out,checked_out_time';
				$values = sprintf("'%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",$result->player_id,$result->team_id,$_POST['project_id'],$result->position_number,$result->position_id,$result->weight,$result->height,$result->injury,$result->injury_date,$result->injury_end,$result->injury_detail,$result->suspension,$result->suspension_date,$result->suspension_end,$result->suspension_detail,$result->picture,$result->description,$result->published,$result->checked_out,$result->checked_out_time);
			
				$query = "INSERT INTO #__joomleague_playertool ($names) VALUES ($values)";
				$database->setQuery($query);
				$database->query($query);
			}
		}

		if ($_POST['chance_project']==1) { 
		  $_SESSION["joomleague"] = $_POST['project_id'];
          session_unregister("joomleague_team");
          session_unregister("joomleague_match");
		  mosRedirect('index2.php?option=com_joomleague&act=teamtool');
		}
        else {
	      mosRedirect( "index2.php?option=$option&act=$act" );
		} 

	  break;
      
      case 'assign':
        
        //teams already assigned to a project
        $teams = $project->getTeams();
        
        //we dont need these teams in the first list
        $ids = array();
        foreach($teams as $team){
          $ids[] = $team->id;
        }
        
        $v = (count($ids) > 0)? sprintf("WHERE id not in (%s)", implode(",",$ids)) : "";
        $database->setQuery( "SELECT id, name, description 
                                FROM #__joomleague_teams 
                                  $v 
                               ORDER BY name");
        $results = $database->loadObjectList();
        
        $teams1 = array();
        foreach($results as $result){
            $teams1[] = mosHTML::makeOption($result->id, sprintf("%s (%s)", $result->name,$result->description)); 
        }

        //$tlist1 = mosHTML::selectList( $teams1, 'list1', 'class="inputbox" size="20" multiple="multiple" onDblClick="move(document.adminForm.list1,document.adminForm.list2)" style="width:350px;"','value', 'text','');
        
        $teams2 = array();
        
        
        if(count($teams) > 0){
          foreach($teams as $team){
            $teams2[] = mosHTML::makeOption($team->id, sprintf("%s (%s)",$team->name,$team->description));
          }
        }
        
        //$tlist2 = mosHTML::selectList( $teams2, 'list2','class="inputbox" size="20" multiple="multiple" onDblClick="move(document.adminForm.list2,document.adminForm.list1)" style="width:350px"','value','text','');        
        
        $view = 'components/com_joomleague/templates/edit_assign_teams.tpl.php';    
        $jl_version=$joomleague_version;
        $path=$mosConfig_live_site;
        require 'components/com_joomleague/templates/view.tpl.php'; 
         
      break;
      
      default:
        #list teams2project
        $ordering = '';
        if ($project->project_type == 'DIVISIONS_LEAGUE') $ordering='tl.division_id, d.ordering, name';
        $rows = $project->getTeams($ordering);
        $view = 'components/com_joomleague/templates/edit_list_teamtool.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';  
        
      break;
    }
  break;

  case 'divisions':
    
    switch($task){
      
      case 'new':
      case 'edit':
        $row = new LeagueDivision( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( "index2.php?option=$option");
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }

        //get divisions already in project for parents list
        //support only 2 sublevel, so parent must not have parents themselves
        $query = "SELECT id, name FROM #__joomleague_divisions
        			        WHERE project_id=$project->id AND parent_id=0
                      ORDER BY name";
        $database->setQuery( $query );
        $results = $database->loadObjectList();
        $divisionList[] = mosHTML::makeOption(0, _JL_ADMIN_EDIT_FORM_DIVISIONS_SELECT_PARENT);
        foreach ($results as $result) {
          $divisionList[] = mosHTML::makeOption($result->id, $result->name);
        }

        $order = mosGetOrderingList( "SELECT ordering AS value, name AS text
			                                  FROM #__joomleague_divisions
			                                 WHERE project_id=$project->id
                                       ORDER BY ordering");
        $list = mosHTML::selectList( $order, 'ordering', 'class="inputbox" size="1"','value', 'text', intval( $row->ordering ) );

        $view = 'components/com_joomleague/templates/edit_form_divisions.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';   
        
      break;
      
      case 'save':
        $row = new LeagueDivision( $database );
	      $row->save($_POST, "");
        mosRedirect( "index2.php?option=$option&act=$act");
      break;
      
      case 'cancel':
        $row = new LeagueDivision( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'remove':
        $row = new LeagueDivision( $database );
        $row->bind( $_POST );
        for ($x=0;$x<count($cid);$x++)
        {
        	$row->delete($cid[$x]);
        }
        mosRedirect("index2.php?option=$option&act=$act");
      break;   
      
      case 'orderup':
        $row = new LeagueDivision( $database );
	      $row->load( $cid[0] );
	      $row->move( -1, "" );

	      mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'orderdown':
        $row = new LeagueDivision( $database );
	      $row->load( $cid[0] );
	      $row->move( 1, "" );

	      mosRedirect( "index2.php?option=$option&act=$act" );
      break;      
      
      default:
        
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_divisions AS a");
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );
        
        $database->setQuery( "SELECT a.*, p.name AS parent_name, u.name AS editor
                                FROM #__joomleague_divisions AS a
                                LEFT JOIN #__users AS u ON u.id = a.checked_out
                                LEFT JOIN #__joomleague_divisions AS p ON p.id = a.parent_id
                            WHERE a.project_id=$project->id
                            ORDER BY a.ordering
                               LIMIT $pageNav->limitstart,$pageNav->limit");
        $rows = $database->loadObjectList();  
        $view = 'components/com_joomleague/templates/edit_list_divisions.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php'; 
        
      break;
    }
  
    break;
  
  case 'projects':
    
    switch($task){
      
      case 'copy':
      case 'new':
      case 'edit':
        
        $proj = new JoomLeague($database);
        $proj->load( $cid[0] );
        $doTips_config=$proj->getTemplateConfig("do_tips.tpl");

        if ($proj->checked_out && $proj->checked_out <> $my->id) {
          mosRedirect( "index2.php?option=$option");
        }

        $old_id = '';
        if ($task=='copy') {
    			$old_id = $cid[0];
    			$proj->id='';
    			$proj->current_round='1';
    		}

        if ($cid[0]) {
          $proj->checkout( $my->id );
        }
  
        $leagues[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_LEAGUE );
        $database->setQuery( "SELECT id AS value, name AS text 
                                FROM #__joomleague_leagues 
                            ORDER BY ordering" );
        $leagues = array_merge( $leagues, $database->loadObjectList() );

        $league_list = mosHTML::selectList( $leagues, 'league_id', 'class="inputbox" size="1"','value', 'text', $proj->league_id );
        unset( $leagues );
  
        $seasons[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_SEASON );
        $database->setQuery( "SELECT id AS value, name AS text 
                                FROM #__joomleague_seasons 
                            ORDER BY ordering" );
        $seasons = array_merge( $seasons, $database->loadObjectList() );

        $season_list = mosHTML::selectList( $seasons, 'season_id', 'class="inputbox" size="1"','value', 'text', $proj->season_id );
        unset( $seasons );

        $users[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_ADMIN );
        $database->setQuery( "SELECT id AS value, CONCAT(name, ' (', usertype, ')') AS text 
                                FROM #__users 
                               WHERE usertype = ('Super Administrator') OR usertype = ('Administrator') OR usertype = ('Manager') 
                               ORDER BY gid DESC" );
        $users = array_merge( $users, $database->loadObjectList() );

        $user_list = mosHTML::selectList( $users, 'joomleague_admin', 'class="inputbox" size="1"','value', 'text', $proj->joomleague_admin );
        unset( $users );
        
        $editors[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_EDITOR );
        $database->setQuery( "SELECT id AS value, CONCAT(name, ' (', usertype, ')') AS text 
                                FROM #__users ORDER BY gid DESC" );
        $editors = array_merge( $editors, $database->loadObjectList() );

        $editor_list = mosHTML::selectList( $editors, 'joomleague_editor', 'class="inputbox" size="1"', 'value', 'text', $proj->joomleague_editor );
        unset( $editors );

        $zusatz = 'class="inputbox" size="1"';
        if (!isset($doTips_config["use_tip_admin"]) || $doTips_config["use_tip_admin"]==0) $zusatz .= ' disabled="disabled"';
        $tipadmins[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_TIPPADMIN );
        $database->setQuery( "SELECT u.id AS value, name AS text, tm.user_id
                                FROM #__users u
                                Left Join #__joomleague_tip_members tm ON tm.user_id = u.id and tm.project_id = ".$proj->id."
                                where tm.user_id IS NULL " );
        if ( $tipp_users = $database->loadObjectList() )
          $tipadmins = array_merge( $tipadmins, $tipp_users );

        $tipadmin_list = mosHTML::selectList( $tipadmins, 'tip_admin', $zusatz, 'value', 'text', $proj->tip_admin );
        unset( $tipadmins );

        $database->setQuery( "SELECT count(*) FROM #__fb_categories"); 
        $fb_exist = $database->loadResult();
        if ($fb_exist > 0){
        $fireboards[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_FIREBOARD );
        $database->setQuery( "SELECT id AS value, name AS text 
                                FROM #__fb_categories WHERE parent > 0
                            ORDER BY ordering" );
        $fireboards = array_merge( $fireboards, $database->loadObjectList() );

        $fireboard_list = mosHTML::selectList( $fireboards, 'sb_catid', 'class="inputbox" size="1"','value', 'text', $proj->sb_catid );
        unset( $fireboards );
        }
        else $fireboard_list = '';                  
        
//        $teams[] = mosHTML::makeOption( '0', _JL_ADMIN_EDIT_FORM_PROJECTS_NO_SELECT_FAV_TEAM );

        if($cid[0] > 0){

          $query = "SELECT t.id AS value, t.name AS text
                      FROM #__joomleague_teams t, #__joomleague_team_joomleague tp
                     WHERE t.id = tp.team_id AND tp.project_id = ".$cid[0];
            
          $database->setQuery( $query );
          $teams = $database->loadObjectList();
        }
        else $proj->init();
  
        $tempfavs=explode(",", $proj->fav_team);
  	   
       	foreach($tempfavs AS $tempfav) { $selected[]->value = $tempfav;}
        $team_list = mosHTML::selectList( $teams, 'fav_team[]', 'class="inputbox" size="20" multiple="true"','value', 'text', $selected );
        unset( $teams );
        
        $folder = array();
        $handle=opendir( $mosConfig_absolute_path. '/components/com_joomleague/frontend' ); 
        while ($file = readdir ($handle)) {
          if( $file != "index.html" && $file != "." && $file != ".."){
            $folder[] = mosHTML::makeOption( $file, $file );
          }
        }
        closedir($handle); 
        
        $folder_list = mosHTML::selectList( $folder, 'template', 'class="inputbox" size="1"','value', 'text', $proj->template );
        unset( $folder );
        
        $view = 'components/com_joomleague/templates/edit_form_projects.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php'; 
   
      break;
      
      case 'save':
        $proj = new JoomLeague( $database );
        $temp=$_POST;
        if (count($temp["fav_team"])>0) $temp["fav_team"]=implode(",", $_POST['fav_team']);
        else $temp["fav_team"]="";
        $proj->save($temp, false);
        
        //create new league ?
        if ( $temp['newLeagueCheck'] ) {
          $nl = new League( $database );
          $nl->set( 'name', $_POST['leagueNew'] );
          $nl->store();
          $proj->set( 'league_id', $nl->id );
        }
        
        //create new season ?
        if ( $temp['newSeasonCheck'] ) {
          $sl = new Season( $database );
          $sl->set( 'name', $_POST['seasonNew'] );
          $sl->store();
          $proj->set( 'season_id', $sl->id );
        }
        $proj->store();
        print_r($proj);
        
        //import xml templates settings
        if (isset($_POST['copyTemplate']) && $_POST['copyTemplate']) {
          $template = new TemplateConfig($database);
          
          $query = "SELECT id FROM #__joomleague_template_config WHERE project_id=".$_POST['copyTemplate'];
    		  $database->setQuery($query);
    		  $templates = $database->loadObjectList();
    		  foreach ($templates AS $tp) {
            $template->load($tp->id);
            $template->set( 'project_id', $proj->id );
            $template->set( 'id', NULL );
            $template->store();
          }
        }
        
        mosRedirect( "index2.php?option=$option" );
      break;
      
      case 'copysave':
        copyProject($_POST); 	        
        mosRedirect( "index2.php?option=$option", $project_id );
      break;
            
      case 'apply':
        $row = new JoomLeague( $database );
        $temp=$_POST;
        if (count($temp["fav_team"])>0) $temp["fav_team"]=implode(",", $_POST['fav_team']);
        else $temp["fav_team"]="";
        $row->save($temp, false);
        mosRedirect( "index2.php?option=$option&act=projects&task=edit&cid[0]=$id" );
        
      break;       
      
      case 'remove':
        $row = new JoomLeague( $database );
		    foreach($cid as $cids) {
	        $row->delete($cids);
	        echo "<pre>";
    			$query=sprintf("DELETE FROM #__joomleague_rounds WHERE project_id = %s",$cids);
    			$database->query( $database->setQuery($query));
    			$entrys=$database->getAffectedRows();
    			if ($entrys>0) {
    				echo "<br>$entrys ZUGEH&Ouml;RIGE SPIELTAGE ZUM PROJEKT #".$cids." WURDEN GEL&Ouml;SCHT<br>";
    				$query="OPTIMIZE TABLE #__joomleague_rounds\n
    						FLUSH TABLE #__joomleague_rounds";
    				$database->query( $database->setQuery($query));
    			}
			
    			$query=sprintf("DELETE FROM #__joomleague_matches WHERE project_id = %s",$cids);
    			$database->query( $database->setQuery($query));
    			$entrys=$database->getAffectedRows();
    			if ($entrys>0) {
    				echo "$entrys ZUGEH&Ouml;RIGE SPIELE ZUM PROJEKT #".$cids." WURDEN GEL&Ouml;SCHT<br>";
    				$query="OPTIMIZE TABLE #__joomleague_matches\n
    						FLUSH TABLE #__joomleague_matches";
    				$database->query( $database->setQuery($query));
    			}
			
    			$query=sprintf("DELETE FROM #__joomleague_match_events WHERE project_id = %s",$cids);
    			$database->query( $database->setQuery($query));
    			$entrys=$database->getAffectedRows();
    			if ($entrys>0) {
    				echo "$entrys ZUGEH&Ouml;RIGE EREIGNISSE ZUM PROJEKT #".$cids." WURDEN GEL&Ouml;SCHT<br>";
    				$query="OPTIMIZE TABLE #__joomleague_match_events\n
    						FLUSH TABLE #__joomleague_match_events";
    				$database->query( $database->setQuery($query));
    			}
			
    			$query=sprintf("DELETE FROM #__joomleague_playertool WHERE project_id = %s",$cids);
    			$database->query( $database->setQuery($query));
    			$entrys=$database->getAffectedRows();
    			if ($entrys>0) {
    				echo "$entrys ZUGEH&Ouml;RIGE SPIELER ZUM PROJEKT #".$cids." WURDEN GEL&Ouml;SCHT<br>";
    				$query="OPTIMIZE TABLE #__joomleague_playertool\n
    						FLUSH TABLE #__joomleague_playertool";
    				$database->query( $database->setQuery($query));
    			}
    			
    			$query=sprintf("DELETE FROM #__joomleague_team_joomleague WHERE project_id = %s",$cids);
    			$database->query( $database->setQuery($query));
    			$entrys=$database->getAffectedRows();
    			if ($entrys>0) {
    				echo "$entrys ZUGEH&Ouml;RIGE TEAMS ZUM PROJEKT #".$cids." WURDEN GEL&Ouml;SCHT<br>";
    				$query="OPTIMIZE TABLE #__joomleague_team_joomleague\n
    						FLUSH TABLE #__joomleague_team_joomleague";
    				$database->query( $database->setQuery($query));
    			}
    			
    			$query=sprintf("DELETE FROM #__joomleague_template_config WHERE project_id = %s",$cids);
    			$database->query( $database->setQuery($query));
    			$entrys=$database->getAffectedRows();
    			if ($entrys>0) {
    				echo "$entrys ZUGEH&Ouml;RIGE TEMPLATEKONFIGURATIONEN ZUM PROJEKT #".$cids." WURDEN GEL&Ouml;SCHT<br>";
    				$query="OPTIMIZE TABLE #__joomleague_template_config\n
    						FLUSH TABLE #__joomleague_template_config";
    				$database->query( $database->setQuery($query));
    			}
			
    			$query=sprintf("DELETE FROM #__joomleague_tip_members WHERE project_id = %s",$cids);
    			$database->query( $database->setQuery($query));
    			$entrys=$database->getAffectedRows();
    			if ($entrys>0) {
    				echo "$entrys ZUGEH&Ouml;RIGE TIPPSPIELMITGLIEDER ZUM PROJEKT #".$cids." WURDEN GEL&Ouml;SCHT<br>";
    				$query="OPTIMIZE TABLE #__joomleague_tip_members\n
    						FLUSH TABLE #__joomleague_tip_members";
    				$database->query( $database->setQuery($query));
    			}
    			
    			$query=sprintf("DELETE FROM #__joomleague_tip_results WHERE project_id = %s",$cids);
    			$database->query( $database->setQuery($query));
    			$entrys=$database->getAffectedRows();
    			if ($entrys>0) {
    				echo "$entrys ZUGEH&Ouml;RIGE TIPPS ZUM PROJEKT #".$cids." WURDEN GEL&Ouml;SCHT<br>";
    				$query="OPTIMIZE TABLE #__joomleague_tip_results\n
    						FLUSH TABLE #__joomleague_tip_results";
    				$database->query( $database->setQuery($query));
    			}
    			
    			if ($_SESSION["joomleague"]== $cids) {
            session_unregister("joomleague");
            session_unregister("joomleague_team");
            session_unregister("joomleague_match");
          }
		    }
        echo "<br /><br /><b>You will be redirected to the JoomLeague Administration Homepage in 5 seconds!<b>";?>
        <meta http-equiv="refresh" content="5; url=index2.php?option=com_joomleague"/>
        <?php				
              //mosRedirect("index2.php?option=$option&act=$act");
      break;
      
      case 'cancel':
        $row = new JoomLeague( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( "index2.php?option=$option" );
      break;
      
      case 'publish':
        $row = new JoomLeague( $database );
        $round = $row->publish_array($cid, 1, $my->id);
        mosRedirect("index2.php?option=$option&act=$act");
      break;
      
      case 'unpublish';
        $row = new JoomLeague( $database );
        $round = $row->publish_array($cid, 0, $my->id);
        mosRedirect("index2.php?option=$option&act=$act");
      break;
      
      default:
        
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague AS a");
        $total = $database->loadResult();

        $pageNav = new mosPageNav( $total, $limitstart, $limit  );
        
        $database->setQuery( "SELECT a.*,l.name AS league, s.name AS season, uu.name AS admin, u.name AS editor, uuu.name AS checkoutuser
                                FROM #__joomleague AS a
                           LEFT JOIN #__joomleague_leagues AS l ON l.id = a.league_id
                           LEFT JOIN #__joomleague_seasons AS s ON s.id = a.season_id
                           LEFT JOIN #__users AS uu ON uu.id = a.joomleague_admin
                           LEFT JOIN #__users AS u ON u.id = a.joomleague_editor
                           LEFT JOIN #__users AS uuu ON uuu.id = a.checked_out
                            ORDER BY a.name, l.name, s.name
                               LIMIT $pageNav->limitstart,$pageNav->limit");

        $rows = $database->loadObjectList();        
        
        $view = 'components/com_joomleague/templates/edit_list_projects.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';         

      break;
    }
  
  break;
  
  case 'leagues':
    
    //require_once 'components/com_joomleague/classes/class.League.php';
    
    switch($task){
      
      case 'new':
      case 'edit':
      
        $row = new League( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( "index2.php?option=$option");
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        
        $order = mosGetOrderingList( "SELECT ordering AS value, name AS text
			                                  FROM #__joomleague_leagues
                                    ORDER BY ordering");
    
        $list = mosHTML::selectList( $order, 'ordering', 'class="inputbox" size="1"','value', 'text', intval( $row->ordering ) );
        $selectedvalue=$row->country;
        $countrycode=explode("_", $mosConfig_locale);
        $countries[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_COUNTRY );
        $database->setQuery( "SELECT countries_id, countries_name, countries_iso_code_2, countries_iso_code_3, countries_localname FROM #__joomleague_countries WHERE published = 1");
        $results = $database->loadObjectList();
        foreach ($results AS $result) {
        	if (strtoupper($result->countries_iso_code_2)==strtoupper($countrycode[0])) {
        		if (is_null($row->country)) $selectedvalue=$result->countries_id;
        		$value=$result->countries_localname;
        	}
        	else {
        		if (isset($country[$result->countries_iso_code_3])) $value=$country[$result->countries_iso_code_3];
        		else $value=$result->countries_name;
        	}
        	$countries[] = mosHTML::makeOption( $result->countries_id, "$value" );
				}
        $clist = mosHTML::selectList( $countries, 'country', 'class="inputbox" size="1"','value', 'text', $selectedvalue );
        if (is_null($row->country)) $clist.="<b>"._JL_ADMIN_NOT_USED."</b>";
        $view = 'components/com_joomleague/templates/edit_form_leagues.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php'; 
        
      break;
      
      case 'save':
        $row = new League( $database );
        $row->save($_POST, "");
        $row->updateOrder( );
        mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'remove':
        $row = new League( $database );
        $row->bind( $_POST );
        for ($x=0;$x<count($cid);$x++)
        {
        	$row->delete($cid[$x]);
        }
        mosRedirect("index2.php?option=$option&act=$act");
      break;
      
      case 'cancel':
        $row = new League( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'orderup':
        $row = new League( $database );
	      $row->load( $cid[0] );
	      $row->move( -1, "" );

	      mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'orderdown':
        $row = new League( $database );
	      $row->load( $cid[0] );
	      $row->move( 1, "" );

	      mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      default:
        
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_leagues AS a");
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );
        
        $database->setQuery( "SELECT a.*, u.name AS editor
                                FROM #__joomleague_leagues AS a
                           LEFT JOIN #__users AS u ON u.id = a.checked_out
                            ORDER BY a.ordering
                               LIMIT $pageNav->limitstart,$pageNav->limit");
        $rows = $database->loadObjectList();        
        
        $view = 'components/com_joomleague/templates/edit_list_leagues.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';  
        
      break;
    }
    
  break;
    
  case 'seasons':
    
    //require_once 'components/com_joomleague/classes/class.Season.php';
    
    switch($task){
      
      case 'new':
      case 'edit':
        $row = new Season( $database );
        $row->load( $cid[0] );
        
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( "index2.php?option=$option");
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }

        $order = mosGetOrderingList( "SELECT ordering AS value, name AS text
			                                  FROM #__joomleague_seasons
			                              ORDER BY ordering");

        $list = mosHTML::selectList( $order, 'ordering', 'class="inputbox" size="1"','value', 'text', intval( $row->ordering ) );
        
        $view = 'components/com_joomleague/templates/edit_form_seasons.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';  
        
      break;
      
      case 'save':
         $row = new Season( $database );
	     $row->save($_POST, "");
         $row->updateOrder( );
	     mosRedirect( "index2.php?option=$option&act=$act");
      break;
      
      case 'remove':
        $row = new Season( $database );
        $row->bind( $_POST );
        for ($x=0;$x<count($cid);$x++)
        {
        	$row->delete($cid[$x]);
        }
        mosRedirect("index2.php?option=$option&act=$act");
      break;
      
      case 'cancel':
        $row = new Season( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( "index2.php?option=$option&act=$act");
      break;
      
      case 'orderup':
        $row = new Season( $database );
	      $row->load( $cid[0] );
	      $row->move( -1, "" );

	      mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'orderdown':
        $row = new Season( $database );
	      $row->load( $cid[0] );
	      $row->move( 1, "" );

	      mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      default:
        
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_seasons AS a");
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );
        
        $database->setQuery( "SELECT a.*, u.name AS editor
                                FROM #__joomleague_seasons AS a
                           LEFT JOIN #__users AS u ON u.id = a.checked_out
                            ORDER BY a.ordering
                               LIMIT $pageNav->limitstart,$pageNav->limit");
        $rows = $database->loadObjectList();        
        
        $view = 'components/com_joomleague/templates/edit_list_seasons.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';
        
      break;
    }
  
  break;
  
  case 'positions':
    
    //require_once 'components/com_joomleague/classes/class.Position.php';
    
    switch($task){
      
      case 'new':
      case 'edit':
      
        $row = new Position( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( "index2.php?option=$option");
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        
        $order = mosGetOrderingList( "SELECT ordering AS value, name AS text
			                                  FROM #__joomleague_positions
                                    ORDER BY ordering");
    
        $list = mosHTML::selectList( $order, 'ordering', 'class="inputbox" size="1"','value', 'text', intval( $row->ordering ) );
        
        $view = 'components/com_joomleague/templates/edit_form_positions.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php'; 
        
      break;
      
      case 'save':
        $row = new Position( $database );
        $row->save($_POST, "");
        $row->checkin();
        $row->updateOrder();
        mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'cancel':
        $row = new Position( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'remove':
        $row = new Position( $database );
        $row->bind( $_POST );
        for ($x=0;$x<count($cid);$x++)
        {
        	$row->delete($cid[$x]);
        }
        mosRedirect("index2.php?option=$option&act=$act");
      break;            
      
      case 'orderup':
        $row = new Position( $database );
	      $row->load( $cid[0] );
	      $row->move( -1, "" );

	      mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'orderdown':
        $row = new Position( $database );
	      $row->load( $cid[0] );
	      $row->move( 1, "" );

	      mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      default:
        
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_positions AS a");
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );
        
        $database->setQuery( "SELECT a.*, u.name AS editor
                                FROM #__joomleague_positions AS a
                           LEFT JOIN #__users AS u ON u.id = a.checked_out
                            ORDER BY a.ordering
                               LIMIT $pageNav->limitstart,$pageNav->limit");
        $rows = $database->loadObjectList();        
        
        $view = 'components/com_joomleague/templates/edit_list_positions.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';  
        
      break;
    }
    
  break;
  
  case 'eventtypes':
    
    //require_once 'components/com_joomleague/classes/class.Eventtype.php';
    
    switch($task){
      
      case 'new':
      case 'edit':
      
        $row = new Eventtype( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( "index2.php?option=$option");
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }

        $view = 'components/com_joomleague/templates/edit_form_eventtypes.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';  
        
      break;
      
      case 'save':
        $row = new Eventtype( $database );
        $row->save($_POST, "");
        mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'cancel':
        $row = new Eventtype( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'remove':
        $row = new Eventtype( $database );
        $row->bind( $_POST );
        for ($x=0;$x<count($cid);$x++)
        {
        	$row->delete($cid[$x]);
        }
        mosRedirect("index2.php?option=$option&act=$act");
      break;
      
         
      
      default:
              
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );   
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_eventtypes AS a");
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );                   
        
        $database->setQuery( "SELECT a.*, u.name AS editor
                                FROM #__joomleague_eventtypes AS a
                           LEFT JOIN #__users AS u ON u.id = a.checked_out
                           LIMIT $pageNav->limitstart,$pageNav->limit");
        $rows = $database->loadObjectList();        
        
        $view = 'components/com_joomleague/templates/edit_list_eventtypes.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';   
        
      break;
    }
    
  break;
  
  case 'events':
    
    //require_once 'components/com_joomleague/classes/class.MatchEvent.php';
    
    switch($task){
      
      case 'new':
      case 'edit':
      
        $row = new MatchEvent( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( "index2.php?option=$option");
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        
        $view = 'components/com_joomleague/templates/edit_form_events.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';  
        
      break;
      
      case 'save':
        $row = new MatchEvent( $database );
        $row->save($_POST, "");
        mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'cancel':
        $row = new MatchEvent( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      default:
        $rows = array();
        
        $mid = intval(mosGetParam($_REQUEST, 'match',0));
        if($mid > 0){
          $m = new Match($database);
          $m->load($mid);
        
          $database->setQuery( "SELECT e.*, p.firstname, p.lastname, et.name AS eventtype, u.name AS editor
                                FROM #__joomleague_match_events AS e
                           LEFT JOIN #__joomleague_players AS p on p.id = e.player_id
                           LEFT JOIN #__joomleague_eventtypes AS et on et.id = e.event_type_id
                           LEFT JOIN #__users AS u ON u.id = a.checked_out
                               WHERE e.match_id = ".$m->match_id."
                            ORDER BY e.event_time");
          $rows = $database->loadObjectList();        
        }
        
        $view = 'components/com_joomleague/templates/edit_list_events.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php'; 
        
      break;
    }
    
  break;
  
  case 'clubs':
    
    //require_once 'components/com_joomleague/classes/class.Club.php';
    
    switch($task){
      
      case 'new':
      case 'edit':
        $row = new Club( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( "index2.php?option=$option");
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        $selectedvalue=$row->country;
        $countrycode=explode("_", $mosConfig_locale);
        $countries[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_COUNTRY );
        $database->setQuery( "SELECT countries_id, countries_name, countries_iso_code_2, countries_iso_code_3, countries_localname FROM #__joomleague_countries WHERE published = 1");
        $results = $database->loadObjectList();
        foreach ($results AS $result) {
        	if (strtoupper($result->countries_iso_code_2)==strtoupper($countrycode[0])) {
        		if (is_null($row->country)) $selectedvalue=$result->countries_id;
        		$value=$result->countries_localname;
        	}
        	else {
        		if (isset($country[$result->countries_iso_code_3])) $value=$country[$result->countries_iso_code_3];
        		else $value=$result->countries_name;
        	}
        	$countries[] = mosHTML::makeOption( $result->countries_id, "$value" );
				}
        $clist = mosHTML::selectList( $countries, 'country', 'class="inputbox" size="1"','value', 'text', $selectedvalue );
        if (is_null($row->country)) $clist.="<b>"._JL_ADMIN_NOT_USED."</b>";
        $view = 'components/com_joomleague/templates/edit_form_clubs.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';  
               
      break;
      
      case 'save':
        $row = new Club( $database );
	      $row->save($_POST, "");
	      if ($_POST['createTeam'])
        {
          //create a new team with same name as club
          $newTeam = new JL_Team( $database );
          $newTeam->set('name', $row->name);
          $newTeam->set('club_id', $row->id);
          $newTeam->set('short_name', 
                            strtoupper( 
                              substr( ereg_replace("[^a-zA-Z]","",$row->name), 0, 3)
                              )
                      );
          $newTeam->store();
        }
	      mosRedirect( "index2.php?option=$option&act=$act");
      break;
      
      case 'cancel':
        $row = new Club( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'remove':
        $row = new Club( $database );
        $row->bind( $_POST );
        for ($x=0;$x<count($cid);$x++)
        {
        	$row->delete($cid[$x]);
        }
        mosRedirect("index2.php?option=$option&act=$act");
      break;
      
      default:
        
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_clubs AS a");
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );
        
        $database->setQuery( "SELECT a.*, u.name AS editor
                                FROM #__joomleague_clubs AS a
                           LEFT JOIN #__users AS u ON u.id = a.checked_out
                            ORDER BY a.name
                               LIMIT $pageNav->limitstart,$pageNav->limit");
        $rows = $database->loadObjectList();        
        
        $view = 'components/com_joomleague/templates/edit_list_clubs.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';   
        
      break;
    }
  
  break;
  
  case 'teams':
    
    //require_once 'components/com_joomleague/classes/class.Team.php';
    
    switch($task){
      
      case 'new':
      case 'edit':
        $row = new JL_Team( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( "index2.php?option=$option");
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }

        $clubs[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_CLUB );

        $database->setQuery( "SELECT id AS value, name AS text FROM #__joomleague_clubs ORDER BY name");
        $clubs = array_merge( $clubs, $database->loadObjectList() );

        $clist = mosHTML::selectList( $clubs, 'club_id', 'class="inputbox" size="1"','value', 'text', $row->club_id );
        
        $view = 'components/com_joomleague/templates/edit_form_teams.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';   
        
      break;

      case 'save':
        $row = new JL_Team( $database );
	      $row->save($_POST, "");
	      mosRedirect( "index2.php?option=$option&act=$act");
      break;
      
      case 'cancel':
        $row = new JL_Team( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'remove':
        $row = new JL_Team( $database );
        $row->bind( $_POST );
        for ($x=0;$x<count($cid);$x++)
        {
        	$row->delete($cid[$x]);
        }
        mosRedirect("index2.php?option=$option&act=$act");
      break;
      
      default:
        
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        $search = $mainframe->getUserStateFromRequest( "search{$option}{$act}", 'search', '' );
	      $search = $database->getEscaped( trim( strtolower( $search ) ) );
        
        $where = array();
        if ($search) {
            $where[] = "LOWER(a.name) LIKE '$search%'";
	      }
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_teams AS a"
                        . (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
        );
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );
        
        $database->setQuery( "SELECT a.*, c.name AS club, u.name AS editor
                                FROM #__joomleague_teams AS a
                           LEFT JOIN #__users AS u ON u.id = a.checked_out
                           LEFT JOIN #__joomleague_clubs AS c ON a.club_id = c.id"
                           . (count( $where ) ? " WHERE " . implode( ' AND ', $where ) : "").
                          " ORDER BY a.name, club
                               LIMIT $pageNav->limitstart,$pageNav->limit");
        $rows = $database->loadObjectList();
        
        $view = 'components/com_joomleague/templates/edit_list_teams.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php'; 
        
      break;
    }
  
  break;
  
  case 'playertool':
    
    switch($task){
      case 'saveShort':
      for ($x=0;$x<count($cid);$x++)
        {
        	$query="UPDATE #__joomleague_playertool SET 
        	position_number = '".$_POST['position_number'.$cid[$x]]."', 
        	position_id = '".$_POST['position_id'.$cid[$x]]."', 
        	weight = '".$_POST['weight'.$cid[$x]]."', 
        	height = '".$_POST['height'.$cid[$x]]."'
        	WHERE id = ".$cid[$x];
        	$database->setQuery($query);
        	$database->query();
        }
      mosRedirect( "index2.php?option=com_joomleague&act=teamtool");
      case 'edit':
      
        $row = new Playertool( $database );
        $row->load( $cid[0] );
        
        $player = new Player( $database );
        $player->load($row->player_id);
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( "index2.php?option=$option");
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        
        $positions[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_POSITION );

        $database->setQuery( "SELECT id AS value, name AS text FROM #__joomleague_positions order by ordering");
        $positions = array_merge( $positions, $database->loadObjectList() );
        $selectedvalue = 0;
        $position_append = '';
        if ($row->position_id > 0) $selectedvalue = $row->position_id;
        elseif ($player->default_position_id > 0) { $selectedvalue = $player->default_position_id; $position_append = '*';}
        $positionlist = mosHTML::selectList( $positions, 'position_id', 'class="inputbox" size="1"','value', 'text', $selectedvalue );
        
        
        $matchdays[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_MATCHDAY );

        $database->setQuery( "SELECT matchcode AS value, name AS text FROM #__joomleague_rounds WHERE project_id = $project->id order by matchcode");
        $matchdays = array_merge( $matchdays, $database->loadObjectList() );

        $injury_date = mosHTML::selectList( $matchdays, 'injury_date', 'class="inputbox" size="1"','value', 'text', $row->injury_date );
        $injury_end = mosHTML::selectList( $matchdays, 'injury_end', 'class="inputbox" size="1"','value', 'text', $row->injury_end );
        $suspension_date = mosHTML::selectList( $matchdays, 'suspension_date', 'class="inputbox" size="1"','value', 'text', $row->suspension_date );
        $suspension_end = mosHTML::selectList( $matchdays, 'suspension_end', 'class="inputbox" size="1"','value', 'text', $row->suspension_end );
        
        $view = 'components/com_joomleague/templates/edit_form_playertool.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';    
        
      break;
      
      case 'saveAll':
        $team->assignPlayers($project, $_POST);
        mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'saveOne':
        $row = new Playertool( $database );
	      $row->save($_POST, "");
	      mosRedirect( "index2.php?option=$option&act=$act");
      break;
      
      case 'cancel':
        $row = new Playertool( $database );
	      $row->bind( $_POST );
	      $row->checkin();
        mosRedirect("index2.php?option=$option&act=$act");
      break;
      
      case 'assign':
      unset($w, $y, $player1);
        $query = sprintf("SELECT p.id, p.lastname, p.firstname, p.info
                    FROM #__joomleague_players p
               LEFT JOIN #__joomleague_playertool pt on pt.player_id = p.id
                   WHERE team_id = %s AND project_id = %s
                   ORDER BY p.lastname",$team->id, $project->id);
        $database->setQuery($query);
        //print $database->getQuery();
        $playerlist2_result = $database->loadObjectList();
        //print mysql_error();
      
        //we dont need these players in the first list
        $ids = array();
        foreach($playerlist2_result as $player){
          $ids[] = $player->id;
        }
        
        $query = sprintf('SELECT p.id, p.lastname, p.firstname, p.info 
                    FROM #__joomleague_players AS p 
         LEFT OUTER JOIN #__joomleague_playertool AS pt ON pt.player_id = p.id AND pt.project_id=%s
                   WHERE pt.project_id is null
                ORDER BY p.lastname',$project->id);
        
        $database->setQuery( $query );
        $playerlist1_result = $database->loadObjectList();
        
        $player1 = array();
        foreach($playerlist1_result as $result){
            $player1[] = mosHTML::makeOption($result->id, sprintf("%s, %s (%s)", $result->lastname,$result->firstname,$result->info)); 
        }

        //$tlist1 = mosHTML::selectList( $player1, 'list1', 'class="inputbox" size="20" multiple="multiple" onDblClick="move(document.adminForm.list1,document.adminForm.list2)" style="width:350px;"','value', 'text','');
        
        $player2 = array();
        
        if(count($playerlist2_result) > 0){
          foreach($playerlist2_result as $result){
          $player2[] = mosHTML::makeOption($result->id, sprintf("%s, %s (%s)",$result->lastname,$result->firstname,$result->info));
          }
        }
        
        //$tlist2 = mosHTML::selectList( $player2, 'list2','class="inputbox" size="20" multiple="multiple" onDblClick="move(document.adminForm.list2,document.adminForm.list1)" style="width:350px"','value','text','');        
        
        $view = 'components/com_joomleague/templates/edit_assign_players.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';   
        
      break;
    
      default:
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 ); 
        $positions[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_POSITION );

        $database->setQuery( "SELECT id AS value, name AS text FROM #__joomleague_positions order by ordering");
        $positions = array_merge( $positions, $database->loadObjectList() );

        
        $query = sprintf("SELECT count(*)
                            FROM #__joomleague_players p, #__joomleague_playertool pt 
                           WHERE p.id = pt.player_id AND pt.project_id = $project->id AND team_id = $team->id");
        $database->setQuery( $query );
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );            
                
        #list players of a team
        $query = sprintf("SELECT p.*, pt.id AS playertoolid, pt.height, pt.weight, pt.injury AS playertoolinjury, pt.position_id, pt.injury_date AS playertoolinjury_date, 
                          pt.position_number, pt.injury_end AS playertoolinjury_end, pt.checked_out AS checked_out, u.name AS editor
                            FROM #__joomleague_players p, #__joomleague_playertool pt
                           LEFT JOIN #__users AS u ON u.id = pt.checked_out
                           WHERE p.id = pt.player_id AND pt.project_id = $project->id AND team_id = $team->id
                           ORDER BY pt.position_id, pt.position_number, p.lastname
                            LIMIT $pageNav->limitstart,$pageNav->limit");
        $database->setQuery($query);
        $rows = $database->loadObjectList();
        
//        $total = 400;
        
//        include_once( "includes/pageNavigation.php" );
//        $pageNav = new mosPageNav( $total, $limitstart, $limit  );            
        
        $view = 'components/com_joomleague/templates/edit_list_playertool.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';      
        
      break;
    }
  break;
  
  case 'players':
    
    //require_once 'components/com_joomleague/classes/class.Player.php';
    
    switch($task){
      case 'saveShort':
      for ($x=0;$x<count($cid);$x++)
        {
        	$query="UPDATE #__joomleague_players SET 
        	firstname = '".$_POST['firstname'.$cid[$x]]."', 
        	lastname = '".$_POST['lastname'.$cid[$x]]."',
        	birthday = '".$_POST['birthday'.$cid[$x]]."',
        	default_position_id = '".$_POST['default_position_id'.$cid[$x]]."', 
        	default_weight = '".$_POST['default_weight'.$cid[$x]]."', 
        	default_height = '".$_POST['default_height'.$cid[$x]]."',
        	nation = '".$_POST['nation'.$cid[$x]]."',
        	checked_out = 0,
        	checked_out_time = 0 
        	WHERE id = ".$cid[$x];
        	$database->setQuery($query);
        	$database->query();
        }

      mosRedirect( "index2.php?option=com_joomleague&act=players");
      break;
      case 'new':
      case 'edit':
        $row = new Player( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && $my->id != $project->joomleague_admin &&
         $my->id != $project->joomleague_editor && $my->usertype != 'Administrator' && $my->usertype != 'Super Administrator') {
          
          mosRedirect( "index2.php?option=$option");
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        $selectedvalue=$row->nation;
        $countrycode=explode("_", $mosConfig_locale);
        $countries[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_NATIONALITY );
        $database->setQuery( "SELECT countries_id, countries_name, countries_localname, countries_iso_code_2, countries_iso_code_3 FROM #__joomleague_countries ORDER BY published DESC, countries_name, countries_iso_code_3");
        $results = $database->loadObjectList();
        foreach ($results AS $result) {
        	$namevalue=$result->countries_name;
        	if (isset($country[$result->countries_iso_code_3])) $namevalue=$country[$result->countries_iso_code_3];
        	if (strtoupper($result->countries_iso_code_2)==strtoupper($countrycode[0])) {
        		if (is_null($row->nation)||$row->nation==0) $selectedvalue=$result->countries_id;
        		$namevalue=$result->countries_localname;
        	}
        	$value=$result->countries_iso_code_3." ($namevalue)";
        	$countries[] = mosHTML::makeOption( $result->countries_id, "$value" );
				}
        $clist = mosHTML::selectList( $countries, 'nation', 'class="inputbox" size="1"','value', 'text', $selectedvalue );
        $positions[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_POSITION );

          $database->setQuery( "SELECT id AS value, name AS text FROM #__joomleague_positions order by ordering");
          $positions = array_merge( $positions, $database->loadObjectList() );
          $positionlist = mosHTML::selectList( $positions, 'default_position_id', 'class="inputbox" size="1"','value', 'text', $row->default_position_id );
        if (is_null($row->nation)||$row->nation==0) $clist.=_JL_ADMIN_SELECT_COUNTRY_HINT;
        $view = 'components/com_joomleague/templates/edit_form_players.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';   
        
      break;
      
      case 'save':
        $row = new Player( $database );
	      $row->save($_POST, "");
	      mosRedirect( "index2.php?option=$option&act=$act");
      break;
      
      case 'cancel':
        $row = new Player( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( "index2.php?option=$option&act=$act" );
      break;

      case 'remove':
        $row = new Player( $database );
        $row->bind( $_POST );
        for ($x=0;$x<count($cid);$x++)
        {
        	$row->delete($cid[$x]);
        }
        mosRedirect("index2.php?option=$option&act=$act");
      break;      
      
      default:
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        $search = $mainframe->getUserStateFromRequest( "search{$option}{$act}", 'search', '' );
	      $search = $database->getEscaped( trim( strtolower( $search ) ) );
        
        $where = array();
        if ($search) {
            $where[] = "LOWER(a.lastname) LIKE '$search%'";
	      }
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_players AS a"
                          . (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
        );
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );
        
        $database->setQuery( "SELECT a.*, u.name AS editor
                                FROM #__joomleague_players AS a
                           LEFT JOIN #__users AS u ON u.id = a.checked_out"
                           . (count( $where ) ? " WHERE " . implode( ' AND ', $where ) : "").
                          " ORDER BY a.lastname
                               LIMIT $pageNav->limitstart,$pageNav->limit");
        $rows = $database->loadObjectList();
        $positions[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_POSITION );
        $database->setQuery( "SELECT id AS value, name AS text FROM #__joomleague_positions order by ordering");
        $positions = array_merge( $positions, $database->loadObjectList() );
        $selectedvalue=0;
        $countrycode=explode("_", $mosConfig_locale);
        $countries[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_NATIONALITY );
        $database->setQuery( "SELECT countries_id, countries_name, countries_localname, countries_iso_code_2, countries_iso_code_3 FROM #__joomleague_countries ORDER BY published DESC, countries_name, countries_iso_code_3");
        $results = $database->loadObjectList();
        foreach ($results AS $result) {
        	$namevalue=$result->countries_name;
        	if (isset($country[$result->countries_iso_code_3])) $namevalue=$country[$result->countries_iso_code_3];
        	if (strtoupper($result->countries_iso_code_2)==strtoupper($countrycode[0])) {
        	//	if (is_null($row->nation)||$row->nation==0) $selectedvalue=$result->countries_id;
        		$namevalue=$result->countries_localname;
        	}
        	$value=$result->countries_iso_code_3." ($namevalue)";
        	$countries[] = mosHTML::makeOption( $result->countries_id, "$value" );
				}  
        $playerinfos = array();
        if (count($rows)>0) {  
         foreach ($rows AS $row) {
         $query = "SELECT pt.team_id, pt.project_id, t.name AS teamname, p.name AS pname,tt.id AS ttid FROM
        						#__joomleague_playertool AS pt
        						LEFT JOIN #__joomleague AS p ON p.id = pt.project_id
        						LEFT JOIN #__joomleague_seasons AS s ON s.id = p.season_id
        						LEFT JOIN #__joomleague_leagues AS l ON l.id = p.league_id
        						LEFT JOIN #__joomleague_teams AS t ON t.id = pt.team_id
        						LEFT JOIN #__joomleague_team_joomleague AS tt ON pt.team_id = tt.team_id
        						WHERE player_id=".$row->id." GROUP BY pt.project_id ORDER BY s.ordering, l.ordering";
        		$database->setQuery($query);
        		$info=$database->loadObjectList();
        		$playerinfos[$row->id]='';
        		if (count($info)>0) {
              foreach ($info AS $n) {
        			  $playerinfos[$row->id] .= '<b><a href="'.$mosConfig_live_site.'/administrator/index2.php?option=com_joomleague&amp;act=teamtool&amp;cid[0]='.$n->ttid.'&task=setactual&mypp='.$n->project_id.'">'.$n->pname.'</b><br />'.$n->teamname.'</a><br />';
        		  }
        		}
        	}
        }
        $view = 'components/com_joomleague/templates/edit_list_players.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php'; 
        
      break;
    }
  
  break;
  
  case 'playgrounds':
    
    switch($task){
      
      case 'new':
      case 'edit':
        $row = new Playground( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( "index2.php?option=$option");
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }

        // prepare clubselector
        $clubs[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_CLUB );

        $database->setQuery( "SELECT id AS value, name AS text FROM #__joomleague_clubs ORDER BY name");
        $clubs = array_merge( $clubs, $database->loadObjectList() );
        $clist = mosHTML::selectList( $clubs, 'club_id', 'class="inputbox" size="1"','value', 'text', $row->club_id );

				$selectedvalue=$row->country;
				$countrycode=explode("_", $mosConfig_locale);
        $countries[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_COUNTRY );
        $database->setQuery( "SELECT countries_id, countries_name, countries_iso_code_2, countries_iso_code_3, countries_localname FROM #__joomleague_countries WHERE published = 1");
        $results = $database->loadObjectList();
        foreach ($results AS $result) {
        	$value=$result->countries_name;
        	if (isset($country[$result->countries_iso_code_3])) $value=$country[$result->countries_iso_code_3];
        	if (strtoupper($result->countries_iso_code_2)==strtoupper($countrycode[0])) {
        		$value=$result->countries_localname;
        		if (is_null($row->country)) $selectedvalue=$result->countries_id;
        	}
        	$countries[] = mosHTML::makeOption( $result->countries_id, "$value" );
				}
        $countrylist = mosHTML::selectList( $countries, 'country', 'class="inputbox" size="1"','value', 'text', $selectedvalue );
        $view = 'components/com_joomleague/templates/edit_form_playgrounds.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';   
        
      break;
      
      case 'save':
        $row = new Playground( $database );
	      $row->save($_POST, "");
        mosRedirect( "index2.php?option=$option&act=$act");
      break;
      
      case 'cancel':
        $row = new Playground( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'remove':
        $row = new Playground( $database );
        $row->bind( $_POST );
        for ($x=0;$x<count($cid);$x++)
        {
        	$row->delete($cid[$x]);
        }
        mosRedirect("index2.php?option=$option&act=$act");
      break;         
      
      default:
        
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_playgrounds AS a");
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );
        
        $database->setQuery( "SELECT a. * , u.name AS editor, c.name AS club
                                FROM #__joomleague_playgrounds AS a
                                LEFT JOIN #__users AS u ON u.id = a.checked_out
                                LEFT JOIN #__joomleague_clubs AS c ON c.id = a.club_id
                            ORDER BY a.name
                               LIMIT $pageNav->limitstart,$pageNav->limit");
        $rows = $database->loadObjectList();        
        
        $view = 'components/com_joomleague/templates/edit_list_playgrounds.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php'; 
        
      break;
    }
  
  break;

  case 'referees':
    
    //require_once 'components/com_joomleague/classes/class.Player.php';
    
    switch($task){
      
      case 'new':
      case 'edit':
        $row = new Referee( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( "index2.php?option=$option");
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        $selectedvalue=$row->nation;
        $countrycode=explode("_", $mosConfig_locale);
        $countries[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_NATIONALITY );
        $database->setQuery( "SELECT countries_id, countries_name, countries_localname, countries_iso_code_2, countries_iso_code_3 FROM #__joomleague_countries ORDER BY countries_iso_code_3");
        $results = $database->loadObjectList();
        foreach ($results AS $result) {
        	$namevalue=$result->countries_name;
        	if (isset($country[$result->countries_iso_code_3])) $namevalue=$country[$result->countries_iso_code_3];
        	if (strtoupper($result->countries_iso_code_2)==strtoupper($countrycode[0])) {
        		if (is_null($row->nation)||$row->nation==0) $selectedvalue=$result->countries_id;
        		$namevalue=$result->countries_localname;
        	}
        	$value=$result->countries_iso_code_3." ($namevalue)";
        	$countries[] = mosHTML::makeOption( $result->countries_id, "$value" );
				}
        $clist = mosHTML::selectList( $countries, 'nation', 'class="inputbox" size="1"','value', 'text', $selectedvalue );
        if (is_null($row->nation)||$row->nation==0) $clist.=_JL_ADMIN_SELECT_COUNTRY_HINT;
        $view = 'components/com_joomleague/templates/edit_form_referees.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php';   
        
      break;
      
      case 'save':
        $row = new Referee( $database );
	      $row->save($_POST, "");
        mosRedirect( "index2.php?option=$option&act=$act");
      break;
      
      case 'cancel':
        $row = new Referee( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( "index2.php?option=$option&act=$act" );
      break;
      
      case 'remove':
        $row = new Referee( $database );
        $row->bind( $_POST );
        for ($x=0;$x<count($cid);$x++)
        {
        	$row->delete($cid[$x]);
        }
        mosRedirect("index2.php?option=$option&act=$act");
      break;         
      
      default:
        
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        
        $search = $mainframe->getUserStateFromRequest( "search{$option}{$act}", 'search', '' );
	      $search = $database->getEscaped( trim( strtolower( $search ) ) );
        
        $where = array();
        if ($search) {
            $where[] = "LOWER(a.lastname) LIKE '$search%'";
	      }
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_referees AS a". (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : ""));
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );
        
        $database->setQuery( "SELECT a.*, u.name AS editor
                                FROM #__joomleague_referees AS a
                           LEFT JOIN #__users AS u ON u.id = a.checked_out"
                           . (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "").
                           " ORDER BY a.lastname
                               LIMIT $pageNav->limitstart,$pageNav->limit");
        $rows = $database->loadObjectList();        
        
        $view = 'components/com_joomleague/templates/edit_list_referees.tpl.php';    
        $jl_version=$joomleague_version;
        require 'components/com_joomleague/templates/view.tpl.php'; 
        
      break;
    }
    break;
  
  case 'JLexport':
    if ($project) {
      $output = '<?xml version="1.0" encoding="'.substr(_ISO,8).'"?>'."\n";
      $output.= $project->toXML();
      $file = fopen('components/com_joomleague/imports/project_export.jlg','w+');
      if (fwrite($file, $output ) === FALSE) {
        echo "Cannot write to file ($filename)";
        exit;
      }
      fclose($file);
      mosRedirect('components/com_joomleague/imports/project_export.jlg');
    }
    else {
      mosRedirect( "index2.php?option=$option" );
    }
    break;
    
  case 'positionEventType':
  	managePositionEventType($task);
  	
    break;
}

function copyProject( $post ) {
	global $database;
	
  $name = mosGetParam($_POST, "name","copy");
  $league_id = mosGetParam($_POST, "league_id", 0);
  $season_id = mosGetParam($_POST, "season_id", 0);
  $old_id = mosGetParam($_POST, "old_id", 0);
  
  //check project unicity if season and league are not both new
  if ( $league_id && $season_id) {
	  $query = "SELECT id FROM #__joomleague
	              WHERE name = '$name'
	              AND league_id = '$league_id'
	              AND season_id = '$season_id'";
	  $database->setQuery($query);
	  $database->query($query);
	  $num = $database->getAffectedRows();
	  if ($num>0) {
	  	mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=projects&task=copy&cid[0]=".$old_id, "This project already exists" );
	    return;
	  }
  }

  $project = new Joomleague($database);
  $project->bind($_POST);

  //create new league if requested
  if ( mosGetParam($_POST, "newLeagueCheck", 0) ) {
  	$query = "SELECT MAX(ordering) AS ordering FROM #__joomleague_leagues";
  	$database->setQuery($query);
  	$ordering = $database->loadResult()+1;

  	$newLeague = mosGetParam($_POST, "leagueNew", "new league");
    
  	$league = new League($database);
  	$league->set('name', $newLeague);  	
    $league->set('ordering', $ordering);
    $league->store();
    $league_id = $league->get('id');
    //update project object
    $project->set('league_id', $league_id);
  }
  //create new season if requested
  if ( mosGetParam($_POST, "newSeasonCheck", 0) ) {
    $query = "SELECT MAX(ordering) AS ordering FROM #__joomleague_seasons";
    $database->setQuery($query);
    $ordering = $database->loadResult()+1;

    $newSeason = mosGetParam($_POST, "seasonNew", "new season");
    
    $season = new Season($database);
    $season->set('name', $newSeason);   
    $season->set('ordering', $ordering);
    $season->store();
    $season_id = $season->get('id');
    //update project object
    $project->set('season_id', $season_id);
  }
  //TODO: save fav team too...
  //save project
  $project->store();
  $id = $project->get('id');
  
  //copy divisions
  $source_to_copy_division = Array( "0" => 0 );
  $database->setQuery("SELECT * FROM #__joomleague_divisions WHERE project_id=$old_id AND parent_id=0");
  if ( $results = $database->loadAssocList() ) {
  	foreach($results as $result) {
      $division = new LeagueDivision($database);
      $division->bind($result);
      $division->set('id', NULL);
      $division->set('project_id', $id);
      if ( $division->store() ) {
      	$source_to_copy_division[$result['id']] = $division->get('id');
      	//subdivisions
      	$database->setQuery("SELECT * FROM #__joomleague_divisions WHERE project_id=$old_id AND parent_id=".$result['id']);		   
        if ( $subs = $database->loadAssocList() ) {
        	foreach ($subs as $sub) {
        		$subdiv = new LeagueDivision($database);
        		$subdiv->bind( $sub );
        		$subdiv->set('id', NULL);
        		$subdiv->set('project_id', $id);
        		$subdiv->set('parent_id', $division->get('id')); 
        		if ( $subdiv->store() ) 
        		  $source_to_copy_division[$sub['id']] = $subdiv->get('id');       		
        	}
        }
      }
  	}
  }
  
  //copy teams
  $database->setQuery("SELECT * FROM #__joomleague_team_joomleague WHERE project_id=$old_id");
  if ( $results = $database->loadAssocList() ) {
    foreach($results as $result) {
      $p_team = new TeamTool($database);
      $p_team->bind($result);
      $p_team->set('id', NULL);
      $p_team->set('project_id', $id);
      $p_team->set('start_points', 0);
      $p_team->set('division_id', $source_to_copy_division[$result['division_id']]);
      if ( !$p_team->store() ) {
      	echo $database->getErrorMsg();
      }
    }
  }
  
  //copy players
  $database->setQuery("SELECT * FROM #__joomleague_playertool WHERE project_id=$old_id");
  if ( $results = $database->loadAssocList() ) {
    foreach($results as $result) {
      $p_player = new PlayerTool($database);
      $p_player->bind($result);
      $p_player->set('id', NULL);
      $p_player->set('project_id', $id);
      $p_player->set('injury', 0);
		  $p_player->set('injury_date', 0);
		  $p_player->set('injury_end', 0);
		  $p_player->set('injury_detail', '');
		  $p_player->set('suspension', 0);
		  $p_player->set('suspension_date', 0);
		  $p_player->set('suspension_end', 0);
		  $p_player->set('suspension_detail', '');
      if ( !$p_player->store() ) {
        echo $database->getErrorMsg();
      }
    }
  }
  
  //copy xml templates settings
  $query = "SELECT id FROM #__joomleague_template_config WHERE project_id=$old_id";
  $database->setQuery($query);
  if ( $templates = $database->loadObjectList() ){
  	$template = new TemplateConfig($database);  
	  foreach ($templates AS $tp) {
	  	$template->load($tp->id);
	  	$template->set( 'project_id', $proj->id );
	  	$template->set( 'id', NULL );
	  	$template->store();
	  }
  }
}

function managePositionEventType($task)
{
	global $my, $mainframe, $mosConfig_list_limit, $option, $act, $database, $mosConfig_live_site;
  global $joomleague, $joomleague_version, $cid;
  
  $positionId = mosGetParam( $_REQUEST, 'posId', 0 );
	//$database = &$joomleague->_db;
	
	switch ($task) {
		case 'add' :
		case 'edit' :
			$position = new Position($database);
			$position->load($positionId);
			
			$row = new PositionEventType( $database );
			if ($cid[0]) $row->load( $cid[0] );
      
			if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
				mosRedirect( "index2.php?option=$option");
			}

			if ($cid[0]) {
				$row->checkout( $my->id );
			}

			$query = "SELECT id AS value, name AS text
                    FROM #__joomleague_eventtypes
                    ORDER BY name";
			$database->setQuery($query);
			$eventtype[] = mosHTML::makeOption( 0, 'Select Event type' );
			if ($result = $database->loadObjectList()) {
				foreach ($result as $r) {
					$eventtype[] = mosHTML::makeOption( $r->value, $r->text );
				}
			}
			$eventList = mosHTML::selectList( $eventtype, 'eventtype_id', 'class="inputbox" size="1"','value', 'text', intval( $row->eventtype_id ) );


			$order = mosGetOrderingList( "SELECT pet.ordering AS value, et.name AS text
                                    FROM #__joomleague_position_eventtype AS pet
                                    INNER JOIN #__joomleague_eventtypes AS et ON pet.eventtype_id = et.id
                                    WHERE pet.position_id = $positionId
                                    ORDER BY ordering");
			$list = mosHTML::selectList( $order, 'ordering', 'class="inputbox" size="1"','value', 'text', $positionId );

			$view = 'components/com_joomleague/templates/edit_form_position_eventtype.tpl.php';
			$jl_version=$joomleague_version;
			require 'components/com_joomleague/templates/view.tpl.php';

			break;

		case 'save':
			$row = new PositionEventType( $database );
			$row->save($_POST, "");
			$row->updateOrder();
			mosRedirect( "index2.php?option=$option&act=$act&posId=$row->position_id");
			break;

		case 'remove':
			$row = new PositionEventType( $database );
			$row->bind( $_POST );
			for ($x=0;$x<count($cid);$x++)
			{
				$row->delete($cid[$x]);
			}
			mosRedirect("index2.php?option=$option&act=$act&posId=$positionId");
			break;

		case 'cancel':
			$row = new PositionEventType( $database );
			$row->bind( $_POST );
			$row->checkin();
			mosRedirect( "index2.php?option=$option&act=$act&posId=$row->position_id");
			break;

		case 'orderup':
			$row = new PositionEventType( $database );
			$row->load( $cid[0] );
			$row->move( -1, "" );

			mosRedirect( "index2.php?option=$option&act=$act&posId=$row->position_id" );
			break;

		case 'orderdown':
			$row = new PositionEventType( $database );
			$row->load( $cid[0] );
			$row->move( 1, "" );

			mosRedirect( "index2.php?option=$option&act=$act&posId=$row->position_id" );
			break;

		default:

			$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
			$limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );

			$database->setQuery( "SELECT count(*) FROM #__joomleague_position_eventtype AS a");
			$total = $database->loadResult();

			$positionId = mosGetParam( $_REQUEST, 'posId', 0 );
      $position = new Position($database);
      $position->load($positionId);

			include_once( "includes/pageNavigation.php" );
			$pageNav = new mosPageNav( $total, $limitstart, $limit  );

			$database->setQuery( "SELECT pet.position_eventtype_id as id, 
			                             pet.checked_out, pet.checked_out_time,
			                             et.name, u.name AS editor
                             FROM #__joomleague_position_eventtype AS pet
                             LEFT JOIN #__users AS u ON u.id = pet.checked_out
                             LEFT JOIN #__joomleague_eventtypes AS et ON et.id = pet.eventtype_id
                             WHERE pet.position_id = $positionId
                              ORDER BY pet.ordering
                                 LIMIT $pageNav->limitstart,$pageNav->limit");
			$rows = $database->loadObjectList();
			//print_r($rows);exit;

			$view = 'components/com_joomleague/templates/edit_list_position_eventtypes.tpl.php';
			$jl_version=$joomleague_version;
			require 'components/com_joomleague/templates/view.tpl.php';

			break;
	}
}
?>
